Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 27 / 53

Describe the relationship.

Connect returned references to the data they borrow.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Lifetime annotations describe relationships between borrows; they do not extend how long a value lives. When a function may return a reference into either of two inputs, an explicit lifetime can say that the result is usable only while the necessary input borrows remain valid. Many common signatures use lifetime elision rules and need no annotation. An owned return is often simpler when the result must live independently. A static string literal is valid for the entire program; a borrowed local String is not.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/lifetimes/src/main.rs
fn longer<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() {
        left
    } else {
        right
    }
}
fn main() {
    let first = String::from("compiler");
    let second = String::from("cargo");
    println!("{}", longer(&first, &second));
}
↳ EXPECTED OUTPUT
compiler
  1. 1

    The same lifetime parameter connects both input references and the output.

  2. 2

    The annotation does not allocate or prolong either String.

  3. 3

    This comparison uses byte length as its explicit metric.

From the extracted rust-workbench folder
cargo run -p lesson_lifetimes

03 Mind the boundary

04 Your next build

A SMALL MISSION

Define a borrowed Label struct with a lifetime and return its text through a method.

Reveal one possible solution +
solutions/lifetimes/src/main.rs
struct Label<'a> {
    text: &'a str,
}
impl<'a> Label<'a> {
    fn text(&self) -> &str {
        self.text
    }
}
fn main() {
    let value = String::from("ready");
    let label = Label { text: &value };
    assert_eq!(label.text(), "ready");
}

05 Check your reasoning

QUICK SIGNAL CHECK

Do lifetime annotations keep a local allocation alive longer?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.