loops - 为什么我不能在两个不同的映射函数中可变地借用一个变量?
问题描述
我在 Rust 中有一个迭代器,它循环 aVec<u8>
并在两个不同的阶段应用相同的函数。我通过将几个地图函数链接在一起来做到这一点。以下是相关代码(其中示例、example_function_1
和example_function_2
分别是替代变量和函数):
注意:example.chunks()
是自定义函数!不是切片上的默认值!
let example = vec![0, 1, 2, 3];
let mut hashers = Cycler::new([example_function_1, example_function_2].iter());
let ret: Vec<u8> = example
//...
.chunks(hashers.len())
.map(|buf| hashers.call(buf))
//...
.map(|chunk| hashers.call(chunk))
.collect();
这是循环器的代码:
pub struct Cycler<I> {
orig: I,
iter: I,
len: usize,
}
impl<I> Cycler<I>
where
I: Clone + Iterator,
I::Item: Fn(Vec<u8>) -> Vec<u8>,
{
pub fn new(iter: I) -> Self {
Self {
orig: iter.clone(),
len: iter.clone().count(),
iter,
}
}
pub fn len(&self) -> usize {
self.len
}
pub fn reset(&mut self) {
self.iter = self.orig.clone();
}
pub fn call(&mut self, buf: Bytes) -> Bytes {
// It is safe to unwrap because it should indefinietly continue without stopping
self.next().unwrap()(buf)
}
}
impl<I> Iterator for Cycler<I>
where
I: Clone + Iterator,
I::Item: Fn(Vec<u8>) -> Vec<u8>,
{
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> {
match self.iter.next() {
next => next,
None => {
self.reset();
self.iter.next()
}
}
}
// No size_hint, try_fold, or fold methods
}
让我感到困惑的是,我第二次引用hashers
它时是这样说的:
error[E0499]: cannot borrow `hashers` as mutable more than once at a time
--> libpressurize/src/password/password.rs:28:14
|
21 | .map(|buf| hashers.call(buf))
| ----- ------- first borrow occurs due to use of `hashers` in closure
| |
| first mutable borrow occurs here
...
28 | .map(|chunk| hashers.call(chunk))
| --- ^^^^^^^ ------- second borrow occurs due to use of `hashers` in closure
| | |
| | second mutable borrow occurs here
| first borrow later used by call
由于没有同时使用可变引用,这不应该起作用吗?
如果需要更多信息/代码来回答这个问题,请告诉我。
解决方案
.map(|buf| hashers.call(buf))
您可能认为在上面的行中,hashers
可变地借用它来称呼它。这是真的(因为Cycler::call
take &mut self
),但这不是编译器错误的原因。在这一行中,hashers
可变地借用来构造闭包|buf| hashers.call(buf)
,并且该借用持续时间与闭包一样长。
因此,当你写
.map(|buf| hashers.call(buf))
//...
.map(|chunk| hashers.call(chunk))
您正在构建两个同时存在的闭包(假设这是std::iter::Iterator::map
)并为每个闭包可变地借用hashers
,这是不允许的。
这个错误实际上是在保护您免受副作用危害:(在纯本地分析中)两个 s 的副作用将以什么顺序执行并不明显,因为s可以对闭包做任何他们喜欢的事情。鉴于您编写的代码,我假设您是故意这样做的,但编译器不知道您知道自己在做什么。call()
map()
(我们甚至无法预测交错将是什么,因为它们是迭代器。在你的内部//...
可能有一个.filter()
步骤导致hashers.call(buf)
在每次调用之间被调用多次hashers.call(chunk)
,或者产生不同数量的其他东西输出大于输入。)
map()
如果您知道您想要“无论何时决定调用它”的副作用的交错,那么您可以通过dianhenglau 的回答证明,通过RefCell
内部可变性或其他内部可变性获得这种自由。
推荐阅读
- arrays - 如何在 Swift 4 中将金字塔类型的字符串转换为双精度数组
- apache-spark - SparkR org.apache.spark.SparkException:R 工作人员意外退出
- java - 获取枚举值数组少指定项
- c++ - 在 QGraphicsScene 中通过鼠标位置获取 QGraphicsItem
- c++ - 如何从终端分离,以便 git 中的 post-receive 钩子完成
- python - Keras Sequential - ValueError:检查目标时出错:预期dense_3具有形状(无,45)但得到的数组具有形状(2868700,1)
- java - 运行来自多个版本但具有相同名称和相同类名的几个 jar
- android - 为什么我不能使用 if 或打开 JSONObject?
- c# - 按列分组以计算 LINQ WPF 中另一列的重复值
- authentication - 为什么 Auth0 存储我的应用程序的用户数据?