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

标签 rust traits

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

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

最佳答案

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

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

关于rust - 为什么 Fn 派生自 FnMut(派生自 FnOnce)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190851/

相关文章:

perl - 如果你有 Traits,你会停止使用接口(interface)、抽象基类和多重继承吗?

scala - 使用泛型强制 Scala 特征的类型

generics - 当泛型类型受到泛型生存期的限制时,这意味着什么?

memory - 在幕后,Rust 中的向量是通过引用还是值返回的?

rust - worker-loader 不能在 react 项目中使用 wasm-loader 和 typescript

rust - 在闭包内共享连接池

rust - Rust 中的 "Subclassing"特征

types - 以特定结构作为参数的特征实现

rust - 尝试使用Rust tokio Framed LinesCodec写入服务器

rust - 如何从实现该特征的结构迭代器中收集特征向量