如何解决为什么不能在两个不同的映射函数中可变地借用变量?
我在Rust中有一个迭代器,它在Vec<u8>
上循环,并在两个不同的阶段应用相同的函数。我通过将几个map函数链接在一起来实现此目的。这是相关的代码(例如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();
这是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,{
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
占用&mut self
),但这不是编译器错误的所在。在这一行中,hashers
是可变地借来的来构造闭包|buf| hashers.call(buf)
,并且借用的持续时间与闭包一样长。
因此,当您编写
.map(|buf| hashers.call(buf))
//...
.map(|chunk| hashers.call(chunk))
您要构造两个同时存在的闭包(假设这是std::iter::Iterator::map
),并为每个闭包可变地借入hashers
,这是不允许的。
此错误实际上是在保护您免受副作用危害:在纯局部分析中,这两个{{{将执行1}},因为call()
的可以对闭包做任何他们想做的事情。给定您编写的代码,我认为您是故意这样做的,但是编译器不知道您知道自己在做什么。
(我们甚至不能仅仅因为它们是迭代器就预测到交错。在map()
内可能有一个//...
步骤,该步骤导致.filter()
在每次调用hashers.call(buf)
或其他会产生与输入数量不同的输出之间被多次调用。)
如果您知道“只要hashers.call(chunk)
决定调用它的副作用之间的交错,那么您就可以通过map()
或其他内部可变性来获得这种自由,例如dianhenglau's answer演示。
这是行不通的,因为可变引用没有同时使用吗?
不。 rules of references指出:“在任何给定时间,您都可以具有一个可变引用或任意数量的不可变引用”,无论它是否同时使用。有关规则背后的原因,请参见此answer。
关于解决方法,由于您确定突变不会同时发生,因此可以按照this chapter中的说明使用std::cell::RefCell
。将代码修改为:
use std::cell::RefCell;
let example = vec![0,1,2,3];
// Remove the "mut",wrap Cycler in RefCell.
let hashers = RefCell::new(Cycler::new([example_function_1,example_function_2].iter()));
let ret: Vec<u8> = example
//...
.chunks(hashers.borrow().len())
// Borrow hashers as immutable inside the closure,then borrow the Cycler as mutable.
.map(|buf| hashers.borrow_mut().call(buf))
//...
.map(|chunk| hashers.borrow_mut().call(chunk))
.collect();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。