作为输出参数
既然可以将闭包作为输入参数,那么将闭包作为输出参数也应该是可行的。但是,匿名闭包类型,顾名思义是未知的,所以我们必须使用 impl Trait
来返回它们。
用于返回闭包的有效 trait 有:
Fn
FnMut
FnOnce
除此之外,必须使用 move
关键字,它表示所有捕获都按值发生。这是必需的,因为任何按引用捕获都会在函数退出后立即被丢弃,从而在闭包中留下无效的引用。
fn create_fn() -> impl Fn() { let text = "Fn".to_owned(); move || println!("This is a: {}", text) } fn create_fnmut() -> impl FnMut() { let text = "FnMut".to_owned(); move || println!("This is a: {}", text) } fn create_fnonce() -> impl FnOnce() { let text = "FnOnce".to_owned(); move || println!("This is a: {}", text) } fn main() { let fn_plain = create_fn(); let mut fn_mut = create_fnmut(); let fn_once = create_fnonce(); fn_plain(); fn_mut(); fn_once(); }
另请参阅
Fn
, FnMut
, 泛型 和 impl Trait。