Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to combine mutable and immutable borrowing inside one method?

This is the code:

struct Bar {
    x : i8
}
struct Foo {
    items : [Bar; 2]
}
impl Foo {
    pub fn update(&mut self, i : i8) {
        let item = &mut self.items[0];
        if self.items[1].x > 0 {
            item.x = i
        }
    }
}

It doesn’t compile:

error[E0503]: cannot use `self.items[_].x` because it was mutably borrowed
  --> src/lib.rs:10:12
   |
9  |         let item = &mut self.items[0];
   |                    ------------------ borrow of `self.items[_]` occurs here
10 |         if self.items[1].x > 0 {
   |            ^^^^^^^^^^^^^^^ use of borrowed `self.items[_]`
11 |             item.x = i
   |             ---------- borrow later used here

I believe I understand why, but what is a workaround? I do need to both modify and read the same piece of data inside the same method.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Not sure what the point in what you are trying to do is, but it can be done like this:

pub fn update(&mut self, i : i8) {
    if self.items[1].x > 0 {
        self.items[0].x = i
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading