Boss lesson · Unit 03
Lifetimes
Tell the compiler which borrow a result comes from
What you practise
- Why the compiler asks, the elision rules, an annotated
longest, a struct that holds a reference,'static
Try a question from this lesson
Pick one
A reference must not outlive the value it points to. Which line does the compiler reject?
let r;
{
let x = 5;
r = &x;
}
println!("{r}");Correct answer
Line 4
Why
x is dropped at the } on line 5, but r is still used on line 6. The error is reported at the borrow: "x does not live long enough". Python would keep x alive instead. Rust never extends a life.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Every reference has a lifetime
A lifetime is the stretch of code in which a reference is used. The value it points to must stay alive for all of it.
Python has no such idea: a value lives as long as anything refers to it. In Rust values die on schedule, and the compiler rejects any reference that would outlast its value. Inside one function it works all of this out silently.
let s = String::from("hi");
let r = &s;
println!("{r}");Concept
An annotation is a claim
Writing 'a changes nothing at run time and keeps nothing alive. It links references in a signature: "the result is valid for as long as both a and b are".
The compiler checks the body against that claim, and then every caller. 'a is generic, like T: each call fills in the real stretch of code.
Concept
The elision rules
Most signatures need no annotations, because the compiler fills them in by three rules.
Each reference parameter gets its own lifetime. With exactly one reference parameter, the result gets that lifetime. With a &self or &mut self parameter, the result gets the lifetime of self. If the result is still undecided, you must write it.
fn first_word(s: &str) -> &str {
s.split(' ').next().unwrap_or("")
}
println!("{}", first_word("hi there"));9 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 2× true or false
- 1× type the answer
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.