为什么 Fn 派生自 FnMut(派生自 FnOnce)?

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

如果您查看 official Rust doc,您会发现特征 Fn 派生自 FnMut,或者,要实现 Fn,您必须实现 FnMut(之后是 FnOnce,因为 FnMut 也是从它派生的)。

为什么会这样?我简直无法理解。是因为您可以将每个 Fn 称为 FnOnceFnMut 吗?

对此最好的参考是优秀的 Finding Closure in Rust 博客 post。我将引用重要部分:

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

当一个函数需要 FnMut 作为输入,但你的闭包只实现了 Fn。 您的闭包不能作为函数的输入。不灵活。

every closure that implements Fn can also implement FnMut

编译器自动为可以实现 Fn 的闭包实现 FnMut 和 FnOnce。因此,闭包可以使用输入为 Fn 或 FnMut 或 FnOnce 的函数。