I have a problem with the borrow checker in the following scenario: First I store an immutable reference to a mutable variable x
, which I later use elsewhere in my code. Now I come to a point where I want to change the value of x
. Knowing that there is an immutable reference to it inside foo.bar
, first I remove the reference by calling foo.bar.clear()
.
Now that there are no immutable borrows, I'd expect that I can mutate the object, but that's not case. I assume that the problem is that the compiler has no way of knowing that clear()
drops the references inside foo.bar
, but I'm clueless how to proceed in this situation.
Minimal example:
struct Foo<'a> {
bar: Vec<&'a i32>
}
fn main() {
let mut x = 42;
let mut foo = Foo { bar: vec![&x] };
// Do immutable stuff with foo.bar[0]... then:
foo.bar.clear();
x += 1;
foo.bar.push(&x);
println!("X is: {}", foo.bar[0]);
}