rustclosures

When does a closure implement Fn, FnMut and FnOnce?


What are the specific conditions for a closure to implement the Fn, FnMut and FnOnce traits?

That is:

For instance, mutating the state of the closure on it's body makes the compiler not implement Fn on it.


Solution

  • The traits each represent more and more restrictive properties about closures/functions, indicated by the signatures of their call_... method, and particularly the type of self:

    A closure |...| ... will automatically implement as many of those as it can.

    These restrictions follow directly from the type of self and the "desugaring" of closures into structs; described in my blog post Finding Closure in Rust.

    For information on closures, see Closures: Anonymous Functions that Can Capture Their Environment in The Rust Programming Language.