As input parameters

While Rust chooses how to capture variables on the fly mostly without type annotation, this ambiguity is not allowed when writing functions. When taking a closure as an input parameter, the closure’s complete type must be annotated using one of a few traits. In order of decreasing restriction, they are:

  • Fn: the closure captures by reference (&T)
  • FnMut: the closure captures by mutable reference (&mut T)
  • FnOnce: the closure captures by value (T)

On a variable-by-variable basis, the compiler will capture variables in the least restrictive manner possible.

For instance, consider a parameter annotated as FnOnce. This specifies that the closure may capture by &T, &mut T, or T, but the compiler will ultimately choose based on how the captured variables are used in the closure.

This is because if a move is possible, then any type of borrow should also be possible. Note that the reverse is not true. If the parameter is annotated as Fn, then capturing variables by &mut T or T are not allowed.

In the following example, try swapping the usage of Fn, FnMut, and FnOnce to see what happens:

1. // A function which takes a closure as an argument and calls it.
2. fn apply<F>(f: F) where
3. // The closure takes no input and returns nothing.
4. F: FnOnce() {
5. // ^ TODO: Try changing this to `Fn` or `FnMut`.

7. f();
8. }

10. // A function which takes a closure and returns an `i32`.
11. fn apply_to_3<F>(f: F) -> i32 where
12. // The closure takes an `i32` and returns an `i32`.
13. F: Fn(i32) -> i32 {

15. f(3)
16. }

18. fn main() {
19. use std::mem;

21. let greeting = "hello";
22. // A non-copy type.
23. // `to_owned` creates owned data from borrowed one
24. let mut farewell = "goodbye".to_owned();

26. // Capture 2 variables: `greeting` by reference and
27. // `farewell` by value.
28. let diary = || {
29. // `greeting` is by reference: requires `Fn`.
30. println!("I said {}.", greeting);

32. // Mutation forces `farewell` to be captured by
33. // mutable reference. Now requires `FnMut`.
34. farewell.push_str("!!!");
35. println!("Then I screamed {}.", farewell);
36. println!("Now I can sleep. zzzzz");

38. // Manually calling drop forces `farewell` to
39. // be captured by value. Now requires `FnOnce`.
40. mem::drop(farewell);
41. };

43. // Call the function which applies the closure.
44. apply(diary);

46. // `double` satisfies `apply_to_3`'s trait bound
47. let double = |x| 2 * x;

49. println!("3 doubled: {}", apply_to_3(double));
50. }

See also:

std:![:mem:](https://www.emoji-cheat-sheet.com/graphics/emojis/mem.png ":mem:"):drop, Fn, FnMut, and FnOnce