当前位置:网站首页>Rust language -- iterators and closures
Rust language -- iterators and closures
2022-07-06 02:44:00 【A pig】
Closure
Anonymous functions that can capture their environment , Closure is a function , The definition of this function can be assigned to a variable
Example — Program for generating custom exercise plan
The goal is : Don't let users wait unnecessarily
fn main(){
// Create closures
let expensive_closure = |num1, num2|{
num1+num2
};
let b = expensive_closure(11, 12);// Call closure
println!("{}", b);//23
}
Closures do not require annotation of the types of parameters and return values , It can be inferred by itself , Of course, you can also manually mark
fn main(){
let expensive_closure = |num1, num2|{
num1+num2
};
let b = expensive_closure(11, 12);// The first call has determined the parameters and return value types of the closure , And it can't be changed
let c = expensive_closure(11.0, 12.0);// Report errors , Because it has been inferred i32, i32
}
To avoid executing a time-consuming function many times, we can use closures and cooperate struct,struct Hold the closure and its call result
struct Cacher<T>
where T:Fn(u32)->u32
{
calculation:T,
value:Option<u32>,
}
impl<T> Cacher<T>
where T:Fn(u32)->u32{//Fn(u32)->u32 Is a closure type
fn new(calculation:T)->Cacher<T>{
Cacher{
calculation,
value:None,
}
}
fn value(&mut self, arg:u32)->u32{
match self.value{
Some(v)=>v,
None=>{
let v = (self.calculation)(arg);
self.value = Some(v);
v
},
}
}
}Closures can capture variables in the same environment as closures , Function can't
move Keyword can force a closure to take ownership of the environment value it uses
fn main(){
let a = 2;
let test1 = |number|{number};
let b = test1(a);// Successfully captured environment variables a
println!("{}", a);// here a The ownership of is not taken away by closures
}fn main(){
let x = vec![1, 2, 3];
let equal_to_x = move |z| z==x;
println!("{:#?}", x);//move Take ownership of environment variables
let y = vec![1, 2, 3];
assert!(equal_to_x(y))
}iterator
Traverse each element : .iter()
iterator trait Only one method is required :next
next: Go down one item at a time
One item of the iterator is returned each time
The returned results are wrapped in Some in
End of the iteration , return None
You can call directly on the iterator next Method
fn main(){
let vec = vec![1, 2, 3];
let mut v1_iter = vec.iter();
assert_eq!(v1_iter.next(), Some(&1));
assert_eq!(v1_iter.next(), Some(&2));
assert_eq!(v1_iter.next(), Some(&3));
assert_eq!(v1_iter.next(), None);
}sum() function
fn main(){
let vec = vec![1, 2, 3];
let v1_iter = vec.iter();
let total:i32 = v1_iter.sum();
println!("sum = {}", total);//6
}map() Method to change an iterator into another iterator
fn main(){
let vec = vec![1, 2, 3];
let v1_iter = vec.iter();
let iter_map:Vec<_> = v1_iter.map(|x|x+1).collect();
println!("{:#?}", iter_map);//2, 3, 4
}filter Method :
Receive a closure , This closure traverses each element of the iterator , return bool type
If the closure returns true: The current element will be contained in filter In the generated iterator , if false Will not be included in filter In the generated iterator
边栏推荐
- [untitled] a query SQL execution process in the database
- 有没有sqlcdc监控多张表 再关联后 sink到另外一张表的案例啊?全部在 mysql中操作
- CSP date calculation
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
- 2345 file shredding, powerful file deletion tool, unbound pure extract version
- Li Kou today's question -729 My schedule I
- 故障分析 | MySQL 耗尽主机内存一例分析
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12
- Looking at the trend of sequence modeling of recommended systems in 2022 from the top paper
- 2022.02.13
猜你喜欢

Yyds dry inventory comparison of several database storage engines
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20](/img/d5/4bce239b522696b5312b1346336b5f.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 20

故障分析 | MySQL 耗尽主机内存一例分析
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 11](/img/6a/398d9cceecdd9d7c9c4613d8b5ca27.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 11
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12](/img/b1/926d9b3d7ce9c5104f3e81974eef07.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12

"Hands on learning in depth" Chapter 2 - preparatory knowledge_ 2.5 automatic differentiation_ Learning thinking and exercise answers

2022 eye health exhibition, vision rehabilitation exhibition, optometry equipment exhibition, eye care products exhibition, eye mask Exhibition
![[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 9](/img/ed/0edff23fbd3880bc6c9dabd31755ac.jpg)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 9

GifCam v7.0 极简GIF动画录制工具中文单文件版

Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I
随机推荐
Day 50 - install vsftpd on ceontos6.8
PMP每日一练 | 考试不迷路-7.5
有没有完全自主的国产化数据库技术
Microservice registration and discovery
Keyword static
Pat 1046 shortest distance (20 points) simulation
The difference between sizeof and strlen in C language
Sword finger offer 30 Stack containing min function
Briefly describe the implementation principle of redis cluster
Spherical lens and cylindrical lens
2022 eye health exhibition, vision rehabilitation exhibition, optometry equipment exhibition, eye care products exhibition, eye mask Exhibition
【若依(ruoyi)】启用迷你导航栏
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
张丽俊:穿透不确定性要靠四个“不变”
2345文件粉碎,文件强力删除工具无捆绑纯净提取版
After changing the GCC version, make[1] appears in the compilation: cc: command not found
RobotFramework入门(二)appUI自动化之app启动
纯Qt版中国象棋:实现双人对战、人机对战及网络对战
Solve 9 with C language × 9 Sudoku (personal test available) (thinking analysis)
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 15