在编写闭包时,需要注意闭包所引用的变量的生命周期。如下所示:
fn main() { let s = String::from("hello");
let f = |x| { // f is a closure
println!("{} {}", s, x);
};
f(String::from("world"));
}
在上例中,闭包f
使用了变量s
。在编译时,会发现错误“borrowed value does not live long enough”。这是因为f
和s
是用不同的生命周期定义的。解决这个问题的方法是将f
和s
的生命周期相匹配:
fn main() { let s = String::from("hello");
let f = move |x| { // f is a closure
println!("{} {}", s, x);
};
f(String::from("world"));
}
这里使用了move
关键字来把所有变量都转移到闭包内,这样就可以让s
和f
具有相同的生命周期,从而避免了编译错误。