Lesson 12
Lifetimes
Every reference you have written so far borrowed a value for a short, obvious stretch of code: one function call, one block. This lesson is about the cases where the stretch is not obvious, and you have to say it yourself.
A Function the Compiler Cannot Check
Write a function that takes two pieces of text and returns whichever one is longer.
fn longest(x: &str, y: &str) -> &str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let a = String::from("hello");
let b = String::from("hi");
println!("{}", longest(&a, &b));
}
This does not compile.
error[E0106]: missing lifetime specifier
--> src/main.rs:1:33
|
1 | fn longest(x: &str, y: &str) -> &str {
| ---- ---- ^ expected named lifetime
| parameter
|
= help: this function's return type contains a borrowed
value, but the signature does not say whether it is
borrowed from `x` or `y`
help: consider introducing a named lifetime parameter
|
1 | fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
| ++++ ++ ++ ++
Nothing is wrong with the body. longest really does return either x or y, and both really are borrowed for as long as main needs the result. The problem is that the compiler will not run the function to find out which one comes back. It only reads the signature, and the signature fn longest(x: &str, y: &str) -> &str does not say whether the returned reference is borrowed from x, from y, or from neither. Without that answer, the compiler cannot check the borrowing rules at the call site, so it refuses to compile the function at all.
Naming a Lifetime
A lifetime is a name for how long a reference stays valid. Writing one does not change how long anything actually lives. It only tells the compiler that two or more references are related, so it can check them together.
A lifetime name starts with an apostrophe. 'a is the usual first choice, the same way T is the usual first choice for a generic type parameter. It is declared in angle brackets after the function name, the same place a type parameter goes.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let a = String::from("hello");
let b = String::from("hi");
println!("{}", longest(&a, &b));
}
hello
-
<'a>declares the lifetime, the same way<T>declares a type parameter. -
x: &'a strandy: &'a strsay that both parameters are borrowed for at least as long as'a. -
-> &'a strsays the value returned is also borrowed for at least as long as'a.
Read this as one promise: whatever 'a turns out to be for a given call, x, y, and the return value are all valid for at least that long. The compiler no longer has to guess which parameter the return value came from. It only has to check that both parameters, and the return value, agree on one shared lifetime, and it can do that from the signature alone.
Key idea
A lifetime is not a new kind of check. Every rule from borrowing still applies.
'aonly gives the compiler a name to write those checks with, for a function whose signature alone does not make the relationship clear.
What the Lifetime Actually Ties Together
'a does not mean “exactly this long”. It means “at least this long”, and the compiler works out the shortest length that satisfies every call. Call longest with two references that are both valid until the end of main, and the whole program compiles.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
let a = String::from("hello");
let result;
{
let b = String::from("hi");
result = longest(&a, &b);
println!("{result}");
}
}
hello
b only lives until the inner block ends, so for this call 'a is the length of the inner block. result is used inside that same block, so every use of it happens while 'a is still valid. Move the println! outside the block instead, and result would be read after 'a has ended.
fn main() {
let a = String::from("hello");
let result;
{
let b = String::from("hi");
result = longest(&a, &b);
}
println!("{result}");
}
error[E0597]: `b` does not live long enough
--> src/main.rs:15:30
|
14 | let b = String::from("hi");
| - binding `b` declared here
15 | result = longest(&a, &b);
| ^^ borrowed value does not
| live long enough
16 | }
| - `b` dropped here while still borrowed
17 |
18 | println!("{result}");
| ------ borrow later used here
a would still be valid at the println!, but 'a has to be short enough to satisfy both references, because the signature ties them together with the same name. b is dropped at the closing brace, so 'a cannot extend past it, and result cannot be read after that point. The error is not new: it is the same “does not live long enough” rule as an ordinary reference, now checked across a function call instead of inside one block.
Lifetime Elision
Writing 'a on every function that takes or returns a reference would be tiring, and most functions do not need it. first_word takes one reference and returns one reference, and the relationship between them is never in doubt: the returned reference can only have come from the one argument there is.
fn first_word(text: &str) -> &str {
match text.split(' ').next() {
Some(word) => word,
None => text,
}
}
fn main() {
let sentence = String::from("borrow before you copy");
println!("{}", first_word(&sentence));
}
borrow
This compiles with no 'a anywhere, even though the compiler is doing exactly the same borrow checking as it did for longest. Lifetime elision is a small set of rules the compiler tries before it asks you to write a lifetime by hand. If one of them settles every reference in the signature, you write nothing. If not, you get the error you saw for longest, and you write 'a yourself.
The Three Elision Rules
Every reference parameter gets its own lifetime, without you writing one.
If there is exactly one input lifetime, it is assigned to every reference in the return type.
If one of the parameters is
&selfor&mut self, the lifetime ofselfis assigned to every reference in the return type.If, after applying all three, some reference in the signature still has no lifetime, the compiler stops and asks you to write one.
first_word is settled by rule 2. There is one reference parameter, text, so its lifetime is the one used for the return type. longest has two reference parameters, so rule 1 gives each one a lifetime of its own, and rule 2 does not apply because there is more than one. Rule 3 does not apply either, because neither parameter is self. Nothing settles the return type, so longest needed 'a written by hand.
Lifetimes in a Struct
A struct can hold a reference instead of an owned value. When it does, every reference field needs a lifetime, the same way a reference parameter did.
struct Excerpt {
part: &str,
}
error[E0106]: missing lifetime specifier
--> src/main.rs:2:11
|
2 | part: &str,
| ^ expected named lifetime parameter
|
help: consider introducing a named lifetime parameter
|
1 ~ struct Excerpt<'a> {
2 ~ part: &'a str,
|
A struct field can never outlive the value it borrows, and the compiler has no function call to read the relationship from, the way it did with longest. It has to be told. The lifetime is declared in angle brackets after the struct name, the same as a generic type parameter, and used on every reference field.
struct Excerpt<'a> {
part: &'a str,
}
impl<'a> Excerpt<'a> {
fn announce(&self, greeting: &str) -> &str {
println!("attention: {greeting}");
self.part
}
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let excerpt = Excerpt { part: first_sentence };
println!("{}", excerpt.part);
println!("{}", excerpt.announce("listen up"));
}
Call me Ishmael
attention: listen up
Call me Ishmael
-
struct Excerpt<'a>declares the lifetime.part: &'a strsays anExcerptcan never outlive the text it borrows. -
impl<'a> Excerpt<'a>repeats the lifetime for the same reason a genericimpl<T>repeatsT: the methods inside need to know what'arefers to. -
announcetakes two references,&selfandgreeting: &str, and returns one. Elision rule 3 applies because one parameter is&self, so the return type is given the lifetime ofselfwith no'awritten on the method at all.greetingis never connected to the return value, and does not need to be:announcealways returnsself.part, nevergreeting. -
excerptcannot outlivenovel, becausefirst_sentenceborrows from it. The compiler checks that the same way it checks any other reference: the struct is dropped no later than the value it borrows.
The Special Lifetime ‘static
'static means a reference is valid for the entire time the program runs. A string literal written directly in the source has this lifetime, because its text is baked into the compiled program itself and never dropped.
fn slogan() -> &'static str {
"built with Rust"
}
fn main() {
println!("{}", slogan());
}
built with Rust
"built with Rust" is a &'static str without you writing anything, because every string literal is. Writing 'static on the return type here only makes that fact explicit, so the caller can see the reference will never go bad.
Key idea
Reach for
'staticonly when a reference truly lasts the whole program, such as a string literal. It is not a general fix for a lifetime error. Turning every stuck'ainto'staticusually means the value should be owned instead of borrowed, not that it lives forever.
Common Mistakes
Adding ‘a Everywhere Out of Habit
A lifetime is only needed when a reference appears in the return type, or in a struct field. A function with reference parameters and no reference in its return type never needs one.
fn print_length(text: &str) {
println!("{} characters", text.len());
}
This already compiles with no 'a, because nothing is returned that could be checked against a parameter. Adding <'a> here would compile too, but it says nothing the compiler did not already know, and it makes the signature harder to read for no reason.
Expecting ‘a to Make a Reference Live Longer
Writing 'a on longest does not stretch b’s lifetime. It only tells the compiler to check x, y, and the return value together. If the value 'a would need to cover is dropped too early, the program still fails to compile, with the same does not live long enough error as any other reference. The fix is never to add more lifetime syntax. It is to make the value live long enough on its own, usually by moving a let earlier or a block boundary later.
Writing Two Different Lifetimes When One Is Needed
longest used the same 'a for both parameters because the function really can return either one. Giving each parameter its own name, 'a and 'b, would compile, but then the return type would have to pick one of them, and the compiler would reject whichever call passed a shorter-lived reference for the other. Use one shared lifetime whenever the return value really could come from more than one parameter.
Reference
| Written as | What it does |
|---|---|
| ‘a | A lifetime name, declared like a type parameter. |
| fn f<‘a>(…) | Ties one or more parameters and the return value to one lifetime. |
| struct S<‘a> | A struct that cannot outlive the value it borrows. |
| ‘static | Valid for the entire time the program runs. |
| Elision rule | What it does |
|---|---|
| Rule 1 | Every reference parameter gets its own lifetime automatically. |
| Rule 2 | One input lifetime is used for every reference in the return type. |
| Rule 3 | With &self or &mut self, its lifetime is used for the return type. |
Check what stuck
The practice sheet for this lesson has 54 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →