Why does the Rust compiler request I constrain a generic type parameter’s lifetime (error E0309)?

What T: 'a is saying is that any references in T must outlive 'a.

What this means is that you can’t do something like:

let mut o: Option<&str> = Some("foo");
let mut nt = NewType { x: &o };  // o has a reference to &'static str, ok.

{
    let s = "bar".to_string();
    let o2: Option<&str> = Some(&s);
    nt.x = &o2;
}

This would be dangerous because nt would have a dangling reference to s after the block. In this case it would also complain that o2 didn’t live long enough either.

I can’t think of a way you can have a &'a reference to something which contains shorter-lifetime references, and clearly the compiler knows this in some way (because it’s telling you to add the constraint). However I think it’s helpful in some ways to spell out the restriction, since it makes the borrow checker less magic: you can reason about it just from just type declarations and function signatures, without having to look at how the fields are defined (often implementation details which aren’t in documentation) or how the implementation of a function.

Leave a Comment