I can't believe I couldn't find a prior question on this, so apologies if it's a duplicate. The ones suggested by the interface all assume that the mutable reference exists on a different struct, but I'm just trying to mutate self with otherwise immutable references. I even feel like I saw this question asked and answered on stack overflow before, but I can't find it!
I put a minimal repro here, but since it's pretty short, I'll include it as well:
struct A<'a> {
string_ref: &'a String,
}
impl<'a> A<'a> {
fn change(&mut self, val: &'a String) {
self.string_ref = val;
}
}
struct B<'a> {
a: A<'a>,
to_add: String,
}
impl<'a> B<'a> {
fn change(&'a mut self) {
self.a.change(&self.to_add);
}
}
fn main() {
let a = A {
string_ref: &"hello".to_string(),
};
let mut b = B {
a,
to_add: "b".to_string(),
};
b.change();
b.change();
}
The compiler error is on the very last line, b.change()
. The error is Cannot borrow 'b' as mutable more than once at a time"
.
I understand that I'm forcing the reference to &mut self to live way too long. So what I don't understand, is how to avoid it! I tried this code for the B::change
method (based on some of the questions here), but ended up with the same error:
fn change<'b: 'a>(&'b mut self) {
self.a.change(&self.to_add);
}
For greater context, in my production code, I'm creating a facade where a struct like A
in my code has several methods that accept a reference to a value. A new wrapper struct, like B
above, stores that struct and a value that is passed into those methods for each of them.