Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Fn derived from FnMut (which is derived from FnOnce)?

Tags:

rust

traits

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?

like image 253
Kapichu Avatar asked Jul 02 '15 17:07

Kapichu


1 Answers

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

like image 148
Shepmaster Avatar answered Oct 20 '22 09:10

Shepmaster