当前位置:网站首页>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
边栏推荐
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 8
- Misc (eternal night), the preliminary competition of the innovation practice competition of the National College Students' information security competition
- Network Security Learning - Web vulnerabilities (Part 1)
- Introduction to robotframework (II) app startup of appui automation
- Advanced technology management - what is the physical, mental and mental strength of managers
- 2345 file shredding, powerful file deletion tool, unbound pure extract version
- 张丽俊:穿透不确定性要靠四个“不变”
- Keyword static
- HDU_ p1237_ Simple calculator_ stack
- [Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 13
猜你喜欢
深度解析链动2+1模式,颠覆传统卖货思维?
Deeply analyze the chain 2+1 mode, and subvert the traditional thinking of selling goods?
Shell脚本更新存储过程到数据库
解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 6
微服务间通信
Installation and use tutorial of cobaltstrike-4.4-k8 modified version
Maturity of master data management (MDM)
Zero basic self-study STM32 wildfire review of GPIO use absolute address to operate GPIO
Black high-end responsive website dream weaving template (adaptive mobile terminal)
随机推荐
微服务间通信
What should we pay attention to when using the built-in tool to check the health status in gbase 8C database?
Which ecology is better, such as Mi family, graffiti, hilink, zhiting, etc? Analysis of five mainstream smart brands
Master data management theory and Practice
解决:AttributeError: ‘str‘ object has no attribute ‘decode‘
技术分享 | undo 太大了怎么办
ReferenceError: primordials is not defined错误解决
Redis delete policy
Black high-end responsive website dream weaving template (adaptive mobile terminal)
【MySQL 15】Could not increase number of max_ open_ files to more than 10000 (request: 65535)
RobotFramework入门(三)WebUI自动化之百度搜索
CobaltStrike-4.4-K8修改版安装使用教程
After changing the GCC version, make[1] appears in the compilation: cc: command not found
Gifcam v7.0 minimalist GIF animation recording tool Chinese single file version
Is there a case where sqlcdc monitors multiple tables and then associates them to sink to another table? All operations in MySQL
How to check the lock information in gbase 8C database?
I changed the driver to 5.1.35, but it is still the same error. I can succeed even now, but I will report this every time I do an SQL operation
[postgraduate entrance examination English] prepare for 2023, learn list5 words
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 12
Déduisez la question d'aujourd'hui - 729. Mon emploi du temps I