RRust By Example
advancedLifetimes

Lifetime Basic

Annotate references with lifetime parameters.

Lifetime Basic

Annotate references with lifetime parameters.

Difficulty

Advanced

Code

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

fn main() {
    let s1 = String::from("long string");
    let result;
    {
        let s2 = String::from("xyz");
        result = longest(s1.as_str(), s2.as_str());
        println!("longest: {}", result);
    }
}

Explanation

Lifetimes tell the compiler how long references are valid.

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 lifetimes category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Lifetimes Examples