Compiling playground v0.0.1 (/playground)
error[E0597]: `*a2` does not live long enough
18 | a2.set_name(b);
| ^^^^^^^^^^^^^^ borrowed value does not live long enough
19 | }
| `*a2` dropped here while still borrowed
| borrow might be used here, when `a2` is dropped and runs the destructor for type `Box<dyn Name<'_>>`
For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` due to previous error
I'm struggling to understand this. Why is this not allowed?
This is a red flag in general and incorrect here, since it means &'a mut User<'a> - that is, "this unique reference must be valid for at least as long as the reference inside User is valid". In other words, call to set_name currently locks the User forever.
You want to use two (in fact, even three, counting the implicit one in &mut self, which is as long as the function call) distinct lifetimes, like this:
Don't use temporary scope-bound loans inside structs. This will make the structs temporary themselves and prevent them from storing data. It will require data to be stored elsewhere, outside of the struct, in the outer scope. It will make a total lifetime mess of your program.
In structs use only self-contained owning types, like String.