闭包什么时候实现 Fn、FnMut 和 FnOnce? [英] When does a closure implement Fn, FnMut and FnOnce?
问题描述
闭包实现Fn
、FnMut
和FnOnce
特征的具体条件是什么?
What are the specific conditions for a closure to implement the Fn
, FnMut
and FnOnce
traits?
即:
- 闭包什么时候不实现
FnOnce
特性? - 闭包什么时候不实现
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.
推荐答案
每个 trait 代表越来越多的关于闭包/函数的限制性属性,由它们的 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
(self
) 是可以调用一次的函数FnMut
(&mut self
) 是可以调用的函数,前提是它们可以&mut
访问其环境Fn
(&self
) 是可以调用的函数,前提是它们只有&
访问其环境
FnOnce
(self
) are functions that can be called onceFnMut
(&mut self
) are functions that can be called if they have&mut
access to their environmentFn
(&self
) are functions that can be called if they only have&
access to their environment
一个闭包<代码>|...|... 将自动实现尽可能多的那些.
A closure |...| ...
will automatically implement as many of those as it can.
- 所有闭包都实现了
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 implementsFnOnce
, 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
的类型和将闭包脱糖"为结构体;在我的博客文章中描述了在 Rust 中寻找闭包.
These restrictions follow directly from the type of self
and the "desugaring" of closures into structs; described in my blog post Finding Closure in Rust.
有关闭包的信息,请参阅闭包:可以捕获其特征的匿名函数Rust 编程语言中的环境.
For information on closures, see Closures: Anonymous Functions that Can Capture Their Environment in The Rust Programming Language.
这篇关于闭包什么时候实现 Fn、FnMut 和 FnOnce?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!