Prior question that this is not a duplicate of:
- cannot borrow `*self` as mutable because it is also borrowed as immutable
- This question is not relevant b/c the answer ended up being "the Rust compiler has a bug", which I'm pretty sure is not the case here.
I have the following structs:
struct Foo {
data: Vec<Bar>,
a: usize,
}
struct Bar {
b: usize
}
Inside impl Foo
, I have the following methods:
fn example(&mut self, c: usize) {
let baz = &mut self.data[c];
let z = self.calc(c);
baz.b = 42 + z;
}
fn calc(&self, x: usize) -> usize {
self.a * x
}
Of course, the Rust compiler throws an error saying roughly "a mutable borrow occurs when you create baz
, then you do an immutable borrow when you call self.calc
and lastly you later use the mutable borrow when you assign to baz.a
.
However, I'm accessing disjoint fields on the struct because calc
never reads from data that is being written to through baz
.
Is there a way to inform the Rust compiler of this?
baz
, and realistic workarounds are going to be similarly case-specific. Do you have an example closer to your actual code in that respect? – Ry-♦