CodeBlanks Logo Icon CodeBlanks

Explicit lifetimes

Specify explicit lifetime parameters with <'a>.

Explicit lifetimes

If a function takes two references and returns one of them, the compiler can't know which one the returned reference depends on. A lifetime parameter says this explicitly:

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

It reads: "the returned reference lives as long as both x and y are valid". Lifetime names are short and lowercase: 'a, 'b.

Checking at the call site

The compiler picks 'a as the shorter of the two arguments' lifetimes. If the result is used longer than that, it errors:

let a = String::from("uzun metin");
let sonuc;
{
    let b = String::from("kısa");
    sonuc = en_uzun(&a, &b);
}
// println!("{sonuc}");   // error: b doesn't live long enough

Even though the result here is actually a, the compiler doesn't look at runtime values; it decides by the contract in the signature.

Practice Longest text

Write the function fn en_uzun<'a>(x: &'a str, y: &'a str) -> &'a str above. Print the result of en_uzun("elma", "karpuz").

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

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

fn main() {
    println!("{}", en_uzun("elma", "karpuz"));
}

Expected output

karpuz

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Does a lifetime parameter change how long a value lives?

  • It decides at runtime
  • No; it only describes the relationship between references Correct answer
  • Yes, it extends it
  • Yes, it shortens it

Explanation: Lifetime annotations are a contract; the compiler checks at call sites whether the contract is kept.

2 Lifetime parameter

Question
fn en_uzun____(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}
Answer
fn en_uzun<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}

Explanation: Lifetime parameters are also declared in angle brackets, with an apostrophe.

3 Syntax and meaning

Term Meaning
<'a> Lifetime parameter
&'a str Reference living for 'a
-> &'a str Return tied to the inputs
E0106 Missing lifetime specifier

All lessons in Intermediate