Lifetime annotations connect the returned reference to the input references it may point at.

Program

Play the program to compare two borrowed strings and return the longer one.

suffix
longest_reference.rs
Replay: real traced execution (multi-file project)
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() { left } else { right }
}

fn main() {
    let left = "rust";
    let suffix = "book";
    let winner = longest(left, suffix);
    println!("{winner}");
}
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() { left } else { right }
}

fn main() {
    let left = "rust";
    let suffix = "guide";
    let winner = longest(left, suffix);
    println!("{winner}");
}
fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() { left } else { right }
}

fn main() {
    let left = "rust";
    let suffix = "rs";
    let winner = longest(left, suffix);
    println!("{winner}");
}
  1. left ← "rust", suffix ← "book"

    5fn main() {6    let lef→ "rust"t = "rust";7    let suffi→ "book"x = "book"; //@suffix="guide", "rs"8    let winner = longest(lef"rust"t, suffi"book"x);9    println!("{winner}");
  2. if left.len() >= right.len()

    1fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {2    if left.len() >= right.len() { lef"rust"t } else { right }3}
  3. winner ← "rust"

    7    let suffix = "book"; //@suffix="guide", "rs"8    let winne→ "rust"r = longest(lef"rust"t, suffi"book"x);9    println!("{winner}");10}
    outputrust
  1. left ← "rust", suffix ← "guide"

    5fn main() {6    let lef→ "rust"t = "rust";7    let suffi→ "guide"x = "guide";8    let winner = longest(lef"rust"t, suffi"guide"x);9    println!("{winner}");
  2. else

    1fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {2    if left.len() >= right.len() { left } else { righ"guide"t }3}
  3. winner ← "guide"

    7    let suffix = "guide";8    let winne→ "guide"r = longest(lef"rust"t, suffi"guide"x);9    println!("{winner}");10}
    outputguide
  1. left ← "rust", suffix ← "rs"

    5fn main() {6    let lef→ "rust"t = "rust";7    let suffi→ "rs"x = "rs";8    let winner = longest(lef"rust"t, suffi"rs"x);9    println!("{winner}");
  2. if left.len() >= right.len()

    1fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {2    if left.len() >= right.len() { lef"rust"t } else { right }3}
  3. winner ← "rust"

    7    let suffix = "rs";8    let winne→ "rust"r = longest(lef"rust"t, suffi"rs"x);9    println!("{winner}");10}
    outputrust
lifetime parameter `'a` names the relationship between input and output references.
borrow return The function returns one of the borrowed inputs, not a new string.
comparison The branch decides which borrowed value is returned.