Skip to content

Basics of Lifetimes

Daniel Cortes edited this page Aug 16, 2024 · 2 revisions

Lifetimes

Refers to how long an owner/reference exists - before Rust decides to reclaim the memory it was using.

Generic Lifetimes/Lifetime Annotations - Extra syntax added in to clarify relationship between different lifetimes.

  1. Every value is 'owned' by a single variable, argument, struct, vector, etc at a time.
  2. When an owner goes out of scope, the value owned by it is dropped (cleaned up in memory).
fn make_and_print_account() {
    let account = Account::new(1, String::from("me"));

    println!("{:#?}", account);
}

fn main() {
    make_and_print_account();
}

Here is a case of When an owner goes out of scope, the value owned by it is dropped (cleaned up in memory).

  1. There cant be references to a value when its owner goes out of scope.
  2. References to a value can't outlive the value they refer to.

At compile time, Rust will ensure that you cannot return a reference to a value that is about to go out of scope.