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. }
  6. // Define a wrapper function satisfying the `Fn` bound
  7. fn function() {
  8. println!("I'm a function!");
  9. }
  10. fn main() {
  11. // Define a closure satisfying the `Fn` bound
  12. let closure = || println!("I'm a closure!");
  13. call_me(closure);
  14. call_me(function);
  15. }

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