fn apply<F>(f: F) where F: Fn()
{
f();
}
// or
fn apply<F>(f: impl Fn())
{
f();
}
fn main() {
let name = "jiangbo";
let say = || println!("hello: {}", name);
apply(say);
}
FnMut
可以通过可变引用捕获。
fn apply<F>(mut f: F) where F: FnMut()
{
f();
}
// or
fn apply<F>(mut f: impl FnMut(u64))
{
f();
}
fn main() {
let mut name = "jiangbo".to_owned();
let say = || {
name.push_str("44");
println!("hello: {:?}", name);
};
apply(say);
}
FnOnce
fn create_fnonce() -> impl FnOnce() {
let text = "FnOnce".to_owned();
move || println!("This is a: {}", text)
}
fn main() {
let fn_once = create_fnonce();
fn_once();
}
案例
简单案例
let closure = |a: i32| -> i32 {
println!("a={}", a);
a
};
println!("closure return {}", closure(10));
// 或
let closure = |a: i32| -> i32 println!("a={}", a);
println!("closure return {}", closure(10));
// 或
let F = |a: i32,b:i32| -> i32 {
println!("a={},b={}", a,b);
a+b
};
println!("a+b={}",F(1,2))
FnOnce闭包案例
fn main(){
let a = Box::new(23);
let call_me = || {
let c = a;
}
call_me();
call_me();// 报错,这个示例中,闭包call_me中发生了所有权的移交(move语义),Box指针所指向的堆内存的所有权从a移交给了c,而随着c离开包后生命周期的结束,该堆内存也被释放掉。环境中的自由变量a在被闭包执行一次之后,就失效了。
}