-2

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.

yegor256
  • 102,010
  • 123
  • 446
  • 597
  • 3
    I suppose there is a reason in your non-toy example - but for your example you could simply do the mutable borrow after the immutable check (e.g. bring `let item...` into the if. (e.g. [this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ed90fce181dea0699081f11accd152a0) works) – T. Kiley Feb 03 '22 at 18:34

1 Answers1

2

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
    }
}
at54321
  • 8,726
  • 26
  • 46