问题
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
?
回答1:
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
andFnOnce
,FnMut
andFnOnce
,- only
FnOnce
.Why? Well, the three closure traits are actually three nested sets: every closure that implements
Fn
can also implementFnMut
(if&self works
,&mut self
also works; proof:&*self
), and similarly every closure implementingFnMut
can also implementFnOnce
. This hierarchy is enforced at the type level
来源:https://stackoverflow.com/questions/31190851/why-is-fn-derived-from-fnmut-which-is-derived-from-fnonce