闭包作为输入参数是可能的,所以返回一个也应该是可能的。然而,闭合返回类型是有问题的,因为Rust目前只支持返回泛型(非通用)类型。匿名闭合类型是,根据定义,未知等返回闭合只能通过使它具体。这可以通过装箱来完成。
有效类型返回也比以前略有不同:
除此之外,move 关键字必须使用这标志着捕获值。这是必需的,因为通过引用任何捕获会尽快丢弃,函数退出后在闭合内是无效的引用。
#![feature(fnbox)] |
use std::boxed::FnBox; |
// Return a closure taking no inputs and returning nothing |
// which implements `FnBox` (capture by value). |
fn create_fnbox() -> Box { |
let text = "FnBox".to_owned(); |
Box::new(move || println!("This is a: {}", text)) |
} |
fn create_fn() -> Box { |
let text = "Fn".to_owned(); |
Box::new(move || println!("This is a: {}", text)) |
} |
fn create_fnmut() -> Box { |
let text = "FnMut".to_owned(); |
Box::new(move || println!("This is a: {}", text)) |
} |
fn main() { |
let fn_plain = create_fn(); |
let mut fn_mut = create_fnmut(); |
let fn_box = create_fnbox(); |
fn_plain(); |
fn_mut(); |
fn_box(); |
} |