Skip to main content

Lifetimes in functions

A lifetime is not a runtime value and costs nothing at all. It is a label the compiler uses to check that a reference never outlives the data it points at.

Most of the time you write no lifetimes, because elision rules fill them in: a function with one reference input gives its output the same lifetime automatically.

You have to write them when the compiler genuinely cannot tell which input a returned reference borrows from — the classic `longest` example below.

Returning a reference with no lifetime

fn longest(a: &str, b: &str) -> &str { // error[E0106]
    if a.len() > b.len() { a } else { b }
}

error[E0106]: missing lifetime specifier

Add `<'a>` and tie the inputs and the output together, or return an owned `String` if the result does not actually borrow from either input.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust