# Lifetimes — Rust

Source: https://www.skillbyai.com/en/rust/o-lifetimes

> Annotating how long references live.

## Connecting inputs and outputs

A **lifetime** describes how long a reference is valid. Usually the compiler infers lifetimes, but when a function returns a reference derived from several inputs, it needs an annotation such as `fn longest<'a>(a: &'a str, b: &'a str) -> &'a str`, meaning the result lives no longer than both inputs. Lifetimes do not change how long values live; they describe relationships so the compiler can reject dangling references. Returning owned data (`String`) avoids annotations entirely.

## A missing lifetime, compile error

I compiled this with Rust 1.99.0 (cargo build); it is meant to fail. The output is trimmed to the error lines. Without an annotation the compiler cannot tell whether the returned reference comes from a or b (E0106) and suggests introducing a named lifetime parameter.

```rust
fn longest(a: &str, b: &str) -> &str {
    if a.len() > b.len() { a } else { b }
}

fn main() {
    println!("{}", longest("pen", "notebook"));
}
```

Output:

```
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:33
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
error: could not compile `demo` (bin "demo") due to 1 previous error
```

## The annotated version, run

I ran this with Rust 1.99.0 (cargo run, edition 2024, standard library only). With 'a tying the result to both inputs, the function compiles and works while both strings are alive.

```rust
// 'a says: the result lives no longer than both inputs
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}

fn main() {
    let x = String::from("fountain pen");
    let result;
    {
        let y = String::from("ink");
        result = longest(&x, &y);
        println!("longest: {result}");
    }
}
```

Output:

```
longest: fountain pen
```

**Quiz:** Do lifetime annotations make values live longer?

- [x] No, they only describe relationships between references
- [ ] Yes, they extend the lifetime
- [ ] Yes, they move values to the heap
- [ ] They disable the borrow checker

*Answer:* No, they only describe relationships between references. Descriptions, not instructions.
