Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

lifetime

Why does the Rust compiler emit an error requesting me to constrain the lifetime of the generic parameter in the following structure?

pub struct NewType<'a, T> {
    x: &'a T,
}
error[E0309]: the parameter type `T` may not live long enough
 --> src/main.rs:2:5
  |
2 |     x: &'a T,
  |     ^^^^^^^^
  |
  = help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
 --> src/main.rs:2:5
  |
2 |     x: &'a T,
  |     ^^^^^^^^

I can fix it by changing to

pub struct NewType<'a, T>
where
    T: 'a,
{
    x: &'a T,
}

I don't understand why it is necessary to add the T: 'a part to the structure definition. I cannot think of a way that the data contained in T could outlive the reference to T. The referent of x needs to outlive the NewType struct and if T is another structure then it would need to meet the same criteria for any references it contains as well.

Is there a specific example where this type of annotation would be necessary or is the Rust compiler just being pedantic?

like image 206
Novus Avatar asked Jul 28 '16 03:07

Novus


1 Answers

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.

like image 110
Chris Emerson Avatar answered Oct 03 '22 06:10

Chris Emerson