Is it possible to have a struct which contains a reference to a value which has a shorter lifetime than the struct?

Viewed 978

Here is a simplified version of what I want to archive:

struct Foo<'a> {
    boo: Option<&'a mut String>,
}

fn main() {
    let mut foo = Foo { boo: None };
    {
        let mut string = "Hello".to_string();
        foo.boo = Some(&mut string);
        foo.boo.unwrap().push_str(", I am foo!");
        foo.boo = None;
    } // string goes out of scope. foo does not reference string anymore

} // foo goes out of scope

This is obviously completely safe as foo.boo is None once string goes out of scope.

Is there a way to tell this to the compiler?

2 Answers
Related