Loading
0xB0Lesson 12 of 17

Lifetimes and borrow-checker reasoning

Understand reference lifetimes and when annotations are required.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use lifetime annotations in a function that returns a borrowed reference.

Lifetimes describe how long references are valid. The borrow checker ensures references never outlive the data they point to. Many lifetimes are inferred, but function signatures that return borrowed values from multiple inputs may need explicit lifetime parameters.

main.rs
1fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
2    if left.len() >= right.len() { left } else { right }
3}
4
5fn main() {
6    let a = String::from("rust");
7    let b = String::from("safe");
8    println!("{}", longest(&a, &b));
9}
Output
rust

Lifetime annotations do not change runtime behavior. They are compile-time relationships that explain which input reference an output reference is tied to.

Try it

Up to 15 XP

Follow a borrowed reference safely

Trace how a borrowed string reference stays valid through a function call.

Message 1 of 3Predicted 0/0
Input references
longest function
borrow checker

Key takeaways

  • Use lifetime annotations in a function that returns a borrowed reference.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Return the longer borrowed word

+25 XP

Complete pick_longer so it returns the longer of two borrowed strings, then print the result.

  • Longer first
  • Longer second
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…