loops - 为什么我不能在两个不同的映射函数中可变地借用变量?

标签 loops rust reference iterator

我在Rust中有一个迭代器,该迭代器遍历Vec<u8>并在两个不同的阶段应用相同的功能。我通过将几个map函数链接在一起来实现此目的。这是相关的代码(示例example_function_1example_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();

这是Cycler的代码:
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))
您可能会想,在上一行中,mutt借用了hashers来调用它。没错(因为Cycler::call采用&mut self),但这不是编译器错误的所在。在这行代码中,hashers是可变地借来的来构造闭包|buf| hashers.call(buf) ,并且借用的持续时间与闭包一样长。
因此,当你写
        .map(|buf| hashers.call(buf))
        //...
        .map(|chunk| hashers.call(chunk))
您要构造两个同时存在的闭包(假设这是std::iter::Iterator::map),并为每个闭包可变地借用hashers,这是不允许的。
这个错误实际上是在保护您免受副作用的危害:(在纯本地分析中),这不是什么命令,将执行两个call()的副作用,因为map()可以执行任何操作像与封闭。给定您编写的代码,我假设您是故意这样做的,但是编译器不知道您知道自己在做什么。
(我们甚至不能仅仅因为它们是迭代器就可以预测交织。在//...内部可能存在一个.filter()步骤,导致每次调用hashers.call(buf)之间多次调用hashers.call(chunk),否则会产生其他东西输出数量与输入数量不同。)
如果您知道希望“每当map()决定调用它”的副作用交织在一起,那么就可以通过RefCell或其他内部可变性来获得这种自由,如dianhenglau's answer所示。

关于loops - 为什么我不能在两个不同的映射函数中可变地借用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63628015/

相关文章:

c - 遍历字符串并在 C 中用空格分隔输入

python - 总结 Pandas 表中的循环结果

rust 扩展内置枚举结果?

rust - 如何匹配 Rust 中的数据类型?

vector - 如何实现包含自身向量的 Cow 的枚举?

java - 对象的引用问题

php - for 循环 vs while 循环 vs foreach 循环 PHP

java - 使用 System.currentTimeMillis() 了解 while 循环终止

c++ - 谁在这里? g++ 还是 Visual Studio 2017?

silverlight - 我可以在 Silverlight 4 项目和标准 ClassLibrary 中使用相同的对象吗?