Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 907
Ramesh Kithsiri HettiArachchi Avatar asked Oct 15 '25 16:10

Ramesh Kithsiri HettiArachchi


1 Answers

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.

like image 139
Solomon Ucko Avatar answered Oct 18 '25 08:10

Solomon Ucko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!