#[derive(Debug)]
struct Shoe {
size: u32,
style: String,
}
fn find_suitable(data: &Vec<Shoe>, test_fn: fn(&Shoe) -> bool) -> Vec<&Shoe> {
let mut res= vec![];
for s in data.iter() {
if test_fn(s) {
res.push(s);
}
}
res
}
fn shoes_in_my_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
shoes.into_iter()
.filter(move |s| s.size == shoe_size)
.collect()
}
fn main() {
let shoes = vec![
Shoe {size: 10, style: String::from("aaa")},
Shoe {size: 13, style: String::from("bbb")},
];
let res = find_suitable(&shoes, |s| {s.size > 5});
println!("res {:?}", res);
}
capture environment
clousure 的作用可以capture enclose函数的变量,有几种capture的方式
move
将变量move到闭包函数中,对应的是 FnOnce
fn move_capture() {
let x = vec![1,2,3];
let equal_to_x = move |z| x == z;
// println!("{:?}", x); this won't compile as x has been moved
let y = vec![1,2,3];
assert_eq!(equal_to_x(y), true);
}
borrow mut
&mut || {}
表示mutable borrow 了 clousure中用到的变量,x, 所以当mutate_x 执行后,任然可以使用x,因为x是 被borrow进了clousure中。
fn mutate_capture() -> Vec<i32> {
let mut x = vec![1, 2, 3];
let mutate_x = &mut |z| x.iter_mut().for_each(|y| *y = *y + z);
mutate_x(1);
println!("{:?}", x);
x
}
clousure as return type
fn create_fn() -> impl Fn() {
let text = "Fn".to_string();
move || println!("this is a {}", text);
}
必须使用 move
关键字,表明clousure补货的变量都是by value,因为当函数结束后,text将会被drop