TLDR: I want to replace a T behind &mut T with a new T that I construct from the old T
Note: please forgive me if the solution to this problem is easy to find. I did a lot of googling, but I am not sure how to word the problem correctly.
Sample code (playground):
struct T { s: String }
fn main() {
let ref mut t = T { s: "hello".to_string() };
*t = T {
s: t.s + " world"
}
}
This obviously fails because the add impl on String takes self by value, and therefore would require being able to move out of T, which is however not possible, since T is behind a reference.
From what I was able to find, the usual way to achieve this is to do something like
let old_t = std::mem::replace(t, T { s: Default::default() });
t.s = old_t + " world";
but this requires that it's possible and feasible to create some placeholder T until we can fill it with real data.
Fortunately, in my use-case I can create a placeholder T, but it's still not clear to me why is an api similar to this not possible:
map_in_place(t, |old_t: T| T { s: old_t.s + " world" });
Is there a reason that is not possible or commonly done?