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

I want to get a returning value from a method inside a loop. But iterator is also borrowed as a mutable. And the method want an immutable reference.

This is a small reproducible code (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();
}

I am getting an error like below:

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

Upvotes: 4

Views: 1381

Answers (1)

Solomon Ucko
Solomon Ucko

Reputation: 6109

If self.get_const() is independent of self.numbers, you can either calculate it outside the loop:

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

or access the field directly:

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

If it depends on self.numbers, you need to use indexing. Make sure to calculate the constant before indexing:

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

You also need to make sure not to insert or remove any values, since that is likely to cause bugs with the indexing.

Upvotes: 2

Related Questions