首页 > 解决方案 > 在向迭代器借为可变后,在循环内借为不可变

问题描述

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

这是一个小的可重现代码(操场链接):

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

标签: rustimmutabilitymutable

解决方案


如果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];
}

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


推荐阅读