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

好久不见. 提交于 2020-01-13 10:34:21

问题


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 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



来源:https://stackoverflow.com/questions/31190851/why-is-fn-derived-from-fnmut-which-is-derived-from-fnonce

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!