gpt4 book ai didi

closures - 如果参数是按值获取的,为什么还要费心使用 `FnMut`?

转载 作者:行者123 更新时间:2023-11-29 07:53:54 38 4
gpt4 key购买 nike

这是来自 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 {}
}

如果参数是按值获取的,为什么还要费心使用 FnMut,因为无论如何都不能改变参数?事实上,为什么在这里甚至允许使用 FnMut?好像只有FnOnce is permitted to do this :

It has been noted that Rust chooses how to capture variables on the fly without annotation. This is all very convenient in normal usage however when writing functions, this ambiguity is not allowed. The closure's complete type, including which capturing type, must be annotated. The manner of capture a closure uses is annotated as one of the following traits:

  • Fn: takes captures by reference (&T)
  • FnMut: takes captures by mutable reference (&mut T)
  • FnOnce: takes captures by value (T)

最佳答案

FnOnceFnMutFn 之间的区别在于函数访问其环境的方式(分别为移动、可变引用、共享引用) .它与访问函数的参数无关。

这里需要

FnMut,因为any方法可能需要多次调用该函数。

有一个paragraph in the Rust book about the implementation of closures .它显示了 self 参数的差异,它本质上是一个包含环境的 struct

关于closures - 如果参数是按值获取的,为什么还要费心使用 `FnMut`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36221302/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com