Lifetimes

Rust by example - Lifetimes

Prevent dangling references.

&i32 a reference &'a i32 a reference with an explicit lifetime &'a mut i32 a mutable reference with an explicit lifetime

// 'static indicates that the data pointed to by the reference lives
// for the _remaining_ lifetime of the running program. It can still
// be coerced to a shorter lifetime.
fn my_string() -> &'static str {
    let s: &'static str = "I have a static lifetime.";
    s
}

fn main() {
    println!("{}", my_string());
}

The generic lifetime 'a will get the concrete lifetime that is equal to the smaller of the lifetimes of x and y:

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

fn main() {
    let (x, y) = ("short", "looooooong");
    println!("{}", longest(x, y));
}

Lifetime Annotations in Struct Definitions and methods


struct ImportantExcerpt<'a> {
    part: &'a str,
}

impl ImportantExcerpt<'_> {
    fn level(&self) -> i32 {
        3
    }
}

fn main() {
    let ie = ImportantExcerpt { part: "a part" };
    println!("{}", ie.level());
}