9

If you look in the official Rust doc, you see that the trait Fn is derived from FnMut, or, to implement Fn, you have to implement FnMut (and after that FnOnce since FnMut also derives from it).

Why is that so? I simply can't comprehend that. Is it because you can call every Fn as a FnOnce or FnMut?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kapichu
  • 3,346
  • 4
  • 19
  • 38

2 Answers2

5

The best reference for this is the excellent Finding Closure in Rust blog post. I'll quote the salient part:

There’s three traits, and so seven non-empty sets of traits that could possibly be implemented… but there’s actually only three interesting configurations:

  • Fn, FnMut and FnOnce,
  • FnMut and FnOnce,
  • only FnOnce.

Why? Well, the three closure traits are actually three nested sets: every closure that implements Fn can also implement FnMut (if &self works, &mut self also works; proof: &*self), and similarly every closure implementing FnMut can also implement FnOnce. This hierarchy is enforced at the type level

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • I just decided to use `IndexMut` instead of `FnMut` for my task, however, I think I spotted an error? Cause, for functions, there's (`FnOnce`), (`FnOnce`, `FnMut`), (`FnOnce`, `FnMut`, `Fn`). Alright, understood. But for the `Index`es it is: (`Index`), (`Index`, `IndexMut`). That's the other way around and a mistake I think, since, when I implement the mutable version, I have to have the immutable version too, which wont work... (Should I open a new question for that or does this comment suffice?) – Kapichu Jul 02 '15 at 20:10
  • @Kapichu it sounds like a different question to me. Specifically because I want to ask you what you mean by "which won't work". I bet that warrants a code snippet, which means it's probably another question. More questions are good - finer grained search results for the future people. – Shepmaster Jul 02 '15 at 20:47
  • Ok I'll do it, this answer to this question helped me then! Thanks! – Kapichu Jul 03 '15 at 13:34
0

When a function need FnMut as input, but your closure only implement Fn. Your closure can not be the input of the function. It is not flexible.

every closure that implements Fn can also implement FnMut

The compiler auto implement FnMut and FnOnce for closure which can implement Fn. So that, the closure can be use of functions who's input is Fn or FnMut or FnOnce.