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
§Notes
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.
§Links
§Sponsors
- 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
§Contact
- New Rustacean:
- Twitter: @newrustacean
- Email: hello@newrustacean.com
- Chris Krycho
- GitHub: chriskrycho
- Twitter: @chriskrycho
§Examples
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.
cast_ref
}
Structs§
- An individual person defined in a way that includes a reference type.
Enums§
- A reference to a number, either integral or floating-point. Goofy, yes.
Functions§
- Get a(n optional) sub-slice of a slice.