RRust By Example
intermediateOwnership

Non-Lexical Lifetimes

Understanding how Rust determines borrow lifetimes.

Non-Lexical Lifetimes

Understanding how Rust determines borrow lifetimes.

Difficulty

Intermediate

Code

rust
fn main() {
    let mut v = vec![1, 2, 3];

    // NLL: borrow ends before the last use
    let first = &v[0];
    println!("first: {}", first);
    // borrow of first ends here (last use)

    v.push(4);
    println!("v: {:?}", v);

    // this works thanks to NLL
    let mut s = String::from("hello");n    let r = &s;
    let len = r.len();
    // r is no longer used after this point
    s.push_str(" world");
    println!("{} (len: {})", s, len);
}

Explanation

NLL allows borrows to end at last use, not scope end.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the ownership category to build a complete understanding of this topic.

More Ownership Examples