Module show_notes::e013

source ·
Expand description

Staying alive

  • Date: April 4, 2016
  • Subject: Reasoning about and using lifetimes in Rust (and why we need them)
  • Audio


Lifetimes are our way of reasoning about how long a given piece of data is available and safe to use in Rust. The reason we don’t have the dangling pointer problem is that we do have lifetimes instead. They’re not magic, they’re just a bit of semantics and syntax that let us specify the rules for how long any given item lives, and how long references to data must be valid.


  • Aleksey Pirogov
  • Chris Palmer
  • Derek Morr
  • Hamza Sheikh
  • Lachlan Collins
  • Leif Arne Storset
  • Luca Schmid
  • Micael Bergeron
  • Pascal Hertleif
  • Ralph Giles (“rillian”)
  • Ralph “FriarTech” Loizzo
  • reddraggone9
  • Ryan Ollos
  • Vesa Kaihlavirta
  • William Roe

(Thanks to the couple people donating who opted out of the reward tier, as well. You know who you are!)

§Become a sponsor



Here’s an example of a function which won’t actually compile. The reason is: the item we’re trying to return a reference to (cast) is created inside the block and therefore goes out of scope at the end of the block. Putting a lifetime declaration on it is irrelevant!

fn bad_ref_in_ref_out<'a>(num_ref: &'a i64) -> &'a f64 {
    // We can create a local binding using the input.
    let cast = *num_ref as f64;
    // We can even create a reference to it.
    let cast_ref: &'a f64 = &cast;
    // What we can't do is return the reference, because `cast` itself will go
    // out of scope on the next line and be cleaned up.


  • An individual person defined in a way that includes a reference type.


  • A reference to a number, either integral or floating-point. Goofy, yes.