在适当分割时,不允许可变借用

问题描述 投票:1回答:1

这里是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应该允许这样做。我想念什么?

rust immutability borrowing
1个回答
0
投票

分割借用仅在一个功能内起作用。不过,在这里,您要借用a中的字段main和闭包中的字段b(除了能够使用和借用外部作用域的变量之外,这是一个独特的功能)。

© www.soinside.com 2019 - 2024. All rights reserved.