RustCurious.com
Rust explained carefully.

Lifetimes Cheat Sheet

YouTube See video 12: Lifetimes

Elided lifetimes

When a function returns a reference, the lifetime can be “elided” (left out) if:

Zero input references

// Returns Data that is valid forever
fn data() -> &'static Data

One input reference

// Returns Data owned by *x
fn get_data(x: &🟥mut? Foo) -> &🟥mut? Data

// Returns Data that is valid forever
fn lookup_data(x: &Foo) -> &'static Data

Multiple input references

// Returns Data owned by *x
fn from_x<'a>(x: &'a mut? Foo, y: &mut? Bar) -> &'a mut? Data

// Returns Data owned by *y
fn from_y<'a>(x: &mut? Foo, y: &'a mut? Bar) -> &'a mut? Data

// Returns Data that might be owned by *x or *y
fn either<'a>(x: &'a mut? Foo, y: &'a mut? Bar) -> &'a mut? Data

// Returns Data that is valid forever
fn neither(x: &mut? Foo, y: &mut? Bar) -> &'static Data

Methods - Self by reference

impl Map {
    // Returns Data owned by *self
    fn get(&🟥mut? self, key: &Key) -> Option<&🟥mut? Data>

    // Returns Data owned by *self or *other
    fn get_or<'a>(&'a mut? self, other: &'a mut? Bar) -> &'a mut? Data
}

impl Key {
    // Returns Data owned by *map
    fn lookup_in<'a>(&self, map: &'a mut? Map) -> &'a mut? Data
}

Struct with a static reference

struct Product {
    data: &'static Data,
}

Struct with shared references

struct Book<'a> {
    title: &'a str,
    author: &'a str,
}

impl<'a> Book<'a> {
    // Returns a reference that outlives self
    fn title(&self) -> &'a str
}

Struct with a mutable reference

struct OccupiedEntry<'a> {
    map: &'a mut Map,
    index: usize,
}

impl<'a> OccupiedEntry<'a> {
    // Returns Data owned by the Map
    fn get(&🟥self) -> &🟥Data

    // Returns Data owned by the Map (borrowed via self)
    fn get_mut(&🟥mut self) -> &🟥mut Data

    // Consumes self, returns a reference that outlives self
    fn into_mut(self) -> &'a mut Data
}

Lifetime bounds

T: 'static means T does not borrow. T must not have any lifetime constraints, so a value of type T can be held indefinitely.

T: 'a means if T is a reference or contains a reference, it must be valid for at least 'a.

'b: 'a means 'b must be valid for at least 'a.