Reputation: 95
Consider the following programm. Why isn't the reference to self dropped after the first call to foo and how can I resolve this issue without changing the mutability of the foo function parameters.
struct MyElement<'a>(&'a u32);
struct MyStruct(u32);
impl MyStruct {
fn foo<'a>(&'a mut self, vec: &mut Vec<MyElement<'a>>) {
vec.push(MyElement(&self.0));
}
}
fn main() {
let mut mystruct = MyStruct(42);
let mut vec = Vec::new();
mystruct.foo(&mut vec);
mystruct.foo(&mut vec);
}
Upvotes: 0
Views: 165
Reputation: 11758
First, your code looks a bit artificial and unnecessarily complicated. When dealing with references you should always strive for the simplest possible solution that achieves your goal, as otherwise things can get messy real quick.
Nonetheless, in your second call to mystruct.foo(&mut vec);
you are effectively trying to do a second mutable borrow of mystruct
, which simply isn't allowed in Rust (and for good reason). If you simply change &'a mut self
to &'a self
, there will be no problem, because Rust allows you to have multiple immutable references to the same value at the same time.
You asked:
how can I resolve this issue without changing the mutability of the foo function parameters
Well, you can't. As I already mentioned, Rust doesn't allow you to have multiple mutable references at the same time. To learn more, see this.
Upvotes: 3