这里是MVE:
struct Test {
a: i32,
b: i32,
}
fn other(x: &mut i32, refs: &Vec<&i32>) {
*x += 1;
}
fn main() {
let mut xes: Vec<Test> = vec![Test { a: 3, b: 5 }];
let mut refs: Vec<&i32> = Vec::new();
for y in &xes {
refs.push(&y.a);
}
xes.iter_mut().for_each(|val| other(&mut val.b, &refs));
}
尽管refs
仅保存对a
中元素的xes
成员的引用,并且函数other
使用b
成员,但生锈会产生以下错误:
warning: unused variable: `refs`
--> /home/ian/Desktop/test.rs:6:23
|
6 | fn other(x: &mut i32, refs: &Vec<&i32>) {
| ^^^^ help: consider prefixing with an underscore: `_refs`
|
= note: `#[warn(unused_variables)]` on by default
error[E0502]: cannot borrow `xes` as mutable because it is also borrowed as immutable
--> /home/ian/Desktop/test.rs:16:5
|
13 | for y in &xes {
| ---- immutable borrow occurs here
...
16 | xes.iter_mut().for_each(|val| other(&mut val.b, &refs));
| ^^^ mutable borrow occurs here ---- immutable borrow later captured here by closure
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
封包有问题吗?通常,splitting borrows应该允许这样做。我想念什么?
分割借用仅在一个功能内起作用。不过,在这里,您要借用a
中的字段main
和闭包中的字段b
(除了能够使用和借用外部作用域的变量之外,这是一个独特的功能)。