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.
>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
}
}