Input functions

Since closures may be used as arguments, you might wonder if the same can be said about functions. And indeed they can! If you declare a function that takes a closure as parameter, then any function that satisfies the trait bound of that closure can be passed as a parameter.

1. // Define a function which takes a generic `F` argument
2. // bounded by `Fn`, and calls it
3. fn call_me<F: Fn()>(f: F) {
4. f();
5. }

7. // Define a wrapper function satisfying the `Fn` bound
8. fn function() {
9. println!("I'm a function!");
10. }

12. fn main() {
13. // Define a closure satisfying the `Fn` bound
14. let closure = || println!("I'm a closure!");

16. call_me(closure);
17. call_me(function);
18. }

As an additional note, the Fn, FnMut, and FnOnce traits dictate how a closure captures variables from the enclosing scope.

See also:

Fn, FnMut, and FnOnce