借用为迭代器可变后,在循环内借用为不可变

Borrow as immutable inside the loop after borrowed as mutable to the iterator

我想从循环内的方法获取返回值。但是迭代器也被借用为可变的。并且该方法需要一个不可变的引用。

这是一个可重现的小代码 (playground link):

struct Foo {
    numbers: Vec<u8>,
    constant: u8
}

impl Foo {
    pub fn new()-> Foo {
        Foo {
            numbers: vec!(1,2,3,4),
            constant: 1
        }
    }

    pub fn get_mut(&mut self){
        for mut nmb in self.numbers.iter_mut() {
            {
                let constant = self.get_const();
            }
        }
    }

    pub fn get_const(&self)-> u8 {
        self.constant
    }
}

fn main() {
    let mut foo = Foo::new();

    foo.get_mut();
}

我收到如下错误:

error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
  --> src/main.rs:17:32
   |
15 |         for  nmb in self.numbers.iter_mut() {
   |                     -----------------------
   |                     |
   |                     mutable borrow occurs here
   |                     mutable borrow later used here
16 |             {
17 |                 let constant = self.get_const();
   |                                ^^^^ immutable borrow occurs here

如果self.get_const()独立于self.numbers,你可以在循环外计算:

let constant = self.get_const();
for mut nmb in self.numbers.iter_mut() {
    // ...
}

或直接访问字段:

for mut nmb in self.numbers.iter_mut() {
    let constant = self.constant;
}

如果依赖self.numbers,则需要使用索引。确保在索引之前计算常量:

for i in 0..self.numbers.len() {
    let constant = self.get_const();
    let nmb = &mut self.numbers[i];
}

您还需要确保不要插入或删除任何值,因为这可能会导致索引错误。