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 {
    // This string literal is stored directly in the binary, and therefore
    // has a `'static` lifetime.
    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:

/// This function takes two string slices, `x` and `y`, both with the same
/// lifetime `'a`. It returns a string slice that is the longer of the two, also
/// with the lifetime `'a`.
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

/// A struct that holds a reference to a string slice.
///
/// The lifetime parameter `'a` specifies that the `ImportantExcerpt`
/// cannot outlive the string slice it references.
struct ImportantExcerpt<'a> {
    part: &'a str,
}

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

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

Related Topics

  • COW.
  • Memory Management.
  • Ownership Borrowing.
  • Rust Patterns.
  • Typecasts.