什么时候关闭实现Fn,FnMut和FnOnce? [英] When does a closure implement Fn, FnMut and FnOnce?

查看:558
本文介绍了什么时候关闭实现Fn,FnMut和FnOnce?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体条件是用于实现 Fn FnMut FnOnce traits?

What are the specific conditions for a closure to implement the Fn, FnMut and FnOnce traits?

即:


  • 何时执行
  • a closure 不实施 FnMut trait?
  • >实现 Fn trait?

  • When does a closure not implement the FnOnce trait?
  • When does a closure not implement the FnMut trait?
  • When does a closure not implement the Fn trait?

关闭它的身体使编译器不实现 Fn

For instance, mutating the state of the closure on it's body makes the compiler not implement Fn on it.

推荐答案

traits每个都表示关于闭包/函数的越来越严格的属性,由它们的 call _... 方法的签名指示,特别是 self

The traits each represent more and more restrictive properties about closures/functions, indicated by the signatures of their call_... method, and particularly the type of self:


  • FnOnce $ c> self )是可以调用一次的函数。

  • FnMut c>& mut self )是可以调用的函数,如果他们有& mut 访问他们的环境

  • Fn & self )是仍然可以调用的函数, $ c>& 访问其环境。

  • FnOnce (self) are functions that can be called once,
  • FnMut (&mut self) are functions that can be called if they have &mut access to their environment
  • Fn (&self) are functions that can still be called if they only have & access to their environment.

.. |


  • 所有闭包都实现 FnOnce :不能被调用一次的闭包不应该具有名称。注意,如果一个闭包只实现 FnOnce ,它只能被调用一次。

  • 闭包不会移出它们的捕获实现 FnMut ,允许它们被多次调用(如果有对函数对象的非条件访问)。

  • 不需要对捕获的唯一/可变访问实现 Fn ,允许它们几乎在所有地方被调用。

  • All closures implement FnOnce: a closure that can't be called once doesn't deserve the name. Note that if a closure only implements FnOnce, it can be called only once.
  • Closures that don't move out of their captures implement FnMut, allowing them to be called more than once (if there is unaliased access to the function object).
  • Closures that don't need unique/mutable access to their captures implement Fn, allowing them to be called essentially everywhere.

这些限制直接来自 self 的类型,并将闭包的desugaring转换为structs(在在Rust中查找关闭)。

These restrictions follow directly from the type of self and the "desugaring" of closures into structs (described in Finding Closure in Rust).

这篇关于什么时候关闭实现Fn,FnMut和FnOnce?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆