I want to manage a collection of objects in another object but I can't predict the lifetime of the elements in this collection.
I found this example in Syntax of Rust lifetime specifier that demonstrates what I can't do:
struct User<'a> {
name: &'a str,
}
// ... impls omitted
struct ChatRoom<'a> {
name: &'a str,
users: HashMap<&'a str, User<'a>>,
}
ChatRoom holds a map of Users. Each User is a copy although the name within User is a shared reference. The User and the ChatRoom have an explicit lifetime so when they are joined the compiler enforces that Users must live longer than the ChatRoom they're going into.
But what if my User was created after the ChatRoom? I can't use lifetimes because the compiler will complain. What if I delete a User before the ChatRoom? I can't do that either.
How can the ChatRoom hold Users who might be created after it or destroyed before it? I vaguely suspect that something could be done with boxes to implement this but Rust's box documentation is quite poor so I am not certain.