root@coding-prodigies:~# โ–Š
// lesson 3 of 12 ยท 20 min

Lifetimes

โš‘ Report an issue with this lesson

Lifetimes tell the compiler how long references stay valid, so it can catch dangling references before your program ever runs:

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

The 'a here says: the returned reference lives at most as long as the shorter of the two input lifetimes. Most of the time the compiler infers lifetimes for you -- you only write them explicitly when a function's signature is ambiguous about how long its inputs and outputs relate.

Try it yourself

Exercise: The longest function below will not compile because the compiler cannot tell how the lifetimes of x, y, and the return value relate. Add the correct lifetime annotation (like 'a) to the signature so it compiles, then complete the body to return the longer of x and y. Call it with "hello" and "hi" and print the result.
Expected output:
hello
rust
Output

      
    

Run your code and get it working before marking this lesson complete.

// that was the last free lesson

9 more lessons โ€” including Project: build a concurrent word counter โ€” and a final exam plus a certificate are waiting.

Unlock the full course โ€” $99.99