这是Rust by Example 的一个例子:
pub trait Iterator {
// The type being iterated over.
type Item;
// `any` takes `&mut self` meaning the caller may be borrowed
// and modified, but not consumed.
fn any<F>(&mut self, f: F) -> bool where
// `FnMut` meaning any captured variable may at most be
// modified, not consumed. `Self::Item` states it takes
// arguments to the closure by value.
F: FnMut(Self::Item) -> bool {}
}
Run Code Online (Sandbox Code Playgroud)
FnMut如果参数是按值取的,为什么要费心使用,因为无论如何都不能改变参数?事实上,为什么FnMut甚至允许在这里?似乎只FnOnce 允许这样做:
已经注意到 Rust 选择如何在没有注释的情况下动态捕获变量。这在正常使用中非常方便,但是在编写函数时,这种歧义是不允许的。必须注释闭包的完整类型,包括哪个捕获类型。闭包使用的捕获方式被注释为以下之一
trait:
Fn: 按引用捕获 (&T)FnMut: 通过可变引用进行捕获 (&mut T)FnOnce: 按值捕获 (T)
| 归档时间: |
|
| 查看次数: |
520 次 |
| 最近记录: |