如何在 FnMut 上下文中使用盒装闭包?
How do you use boxed closures in FnMut contexts?
如何在需要 FnMut
类型的上下文中使用盒装闭包,例如
pub fn main() {
for n in (0..10).map(Box::new(|i| i * 2)) {
println!("{}", n);
}
}
由于 Box
实现了 Deref
特性,您可以简单地取消引用您的 box
ed 函数:
fn main() {
let boxed_fn = Box::new(|i| i * 2);
for n in (0..10).map(*boxed_fn) {
println!("{}", n);
}
}
如何在需要 FnMut
类型的上下文中使用盒装闭包,例如
pub fn main() {
for n in (0..10).map(Box::new(|i| i * 2)) {
println!("{}", n);
}
}
由于 Box
实现了 Deref
特性,您可以简单地取消引用您的 box
ed 函数:
fn main() {
let boxed_fn = Box::new(|i| i * 2);
for n in (0..10).map(*boxed_fn) {
println!("{}", n);
}
}