输入函数
由于闭包可以用作参数,你可能想知道函数是否也可以这样使用。确实可以!如果你声明一个函数,它接受一个闭包作为参数,那么任何满足该闭包的 trait 约束的函数都可以作为参数传递。
// Define a function which takes a generic `F` argument // bounded by `Fn`, and calls it fn call_me<F: Fn()>(f: F) { f(); } // Define a wrapper function satisfying the `Fn` bound fn function() { println!("I'm a function!"); } fn main() { // Define a closure satisfying the `Fn` bound let closure = || println!("I'm a closure!"); call_me(closure); call_me(function); }
另外需要注意的是,Fn
、FnMut
和 FnOnce
trait
规定了闭包如何从封闭作用域捕获变量。