Lifetimes and borrow-checker reasoning
Understand reference lifetimes and when annotations are required.
- 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.
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}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 XPFollow a borrowed reference safely
Trace how a borrowed string reference stays valid through a function call.
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.
Return the longer borrowed word
Complete pick_longer so it returns the longer of two borrowed strings, then print the result.
- Longer first
- Longer second
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…