When are Fn, FnMut, and FnOnce locks implemented?

What are the special closing conditions for implementing the Fn , FnMut and FnOnce ?

I.e:

  • When closure doesn't implement the FnOnce ?
  • When closure doesn't implement the FnMut ?
  • When does closure not implement the Fn trait?

For example, when changing the closing state on it, the compiler body does not implement Fn on it.

+61
closures rust
May 11 '15 at 20:49
source share
1 answer

Each of these features represents more and more restrictive properties about closures / functions, denoted by the signatures of their call_... method and, in particular, by the type self :

  • FnOnce ( self ) are functions that can be called once,
  • FnMut ( &mut self ) are functions that can be called if they have &mut access to their environment
  • Fn ( &self ) are functions that can still be called if they have only & access to their environment.

Closing |...| ... |...| ... will automatically implement as many of them as possible.

  • All closures implement FnOnce : a closure that cannot be called once does not deserve a name. Note that if a closure implements only FnOnce , it can only be called once.
  • Closures that are not derived from their captures are implemented by FnMut , which allows them to be called more than once (if there is an unrealized access to the function object).
  • Closures that do not require unique / variable access to their captures implement Fn , which allows them to be called essentially everywhere.

These restrictions directly follow from the type of self and "desugaring" closures in structures (described in Search for closures in rust ).

For information on closing in Rust since 2017, see the section in the Closures section of the Rust book .

+74
May 14 '15 at 8:15
source share



All Articles