Module show_notes::e013 [] [src]

Staying alive

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.

Sponsors

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

Become a sponsor

Contact

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

Individual

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

Enums

NumericReference

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

Functions

refs_all_around

Get a(n optional) sub-slice of a slice.