Sub topic 10
Lifetimes next to type parameters
This chapter assumes you can write generic functions with trait bounds, and that you know what a reference is and why the borrow checker exists. Lifetimes get a short refresher below. The focus is how they combine with type parameters.
Two kinds of generic parameter
A type parameter such as T stands for "some type, chosen by the caller". A lifetime parameter such as 'a stands for "some region of the program during which a reference is valid, chosen by the caller". Both are declared inside the same angle brackets, and both are resolved at compile time. Lifetimes are erased before code generation. They do not create extra copies of a function the way type parameters do, as the monomorphization chapter explained.
The declaration order is fixed: lifetimes first, then type parameters, then const parameters.
fn longest<'a, T: AsRef<str> + ?Sized>(a: &'a T, b: &'a T) -> &'a T {
if a.as_ref().len() >= b.as_ref().len() {
a
} else {
b
}
}
fn main() {
println!("{}", longest("apple", "fig"));
}Here T is str. The ?Sized relaxes the implicit T: Sized bound so that &str can be passed. The signature says that both arguments and the result are valid for the same region 'a. In practice 'a is the overlap of the two input lifetimes, so the result cannot outlive either input.
What a lifetime parameter promises
A lifetime parameter does not make anything live longer. It only describes a relationship between references, so the compiler can check the body and every caller against it.
Bounds on type parameters and lifetime parameters read the same way:
T: Displaymeans "TimplementsDisplay".T: 'ameans "every reference insideTis valid for at least'a".'b: 'ameans "'blasts at least as long as'a".
A type with no references inside, like i32 or String, satisfies T: 'a for every 'a.
Generic structs that borrow
When a generic struct stores a reference, it needs a lifetime parameter as well. The impl block must declare both parameters again, because impl<...> introduces the names used afterwards.
struct Highlight<'a, T> {
source: &'a [T],
start: usize,
end: usize,
}
impl<'a, T> Highlight<'a, T> {
fn new(source: &'a [T], start: usize, end: usize) -> Self {
Highlight { source, start, end }
}
fn slice(&self) -> &'a [T] {
&self.source[self.start..self.end]
}
}
fn main() {
let data = vec![1, 2, 3, 4, 5];
let h = Highlight::new(&data, 1, 4);
println!("{:?}", h.slice());
}Look at the return type of slice. It is &'a [T], not the elided &'_ [T] tied to &self. The returned slice borrows from data, not from the Highlight value, so it can outlive h. If you wrote &[T] and let elision tie the result to &self, callers would be forced to keep h alive for as long as they use the slice. That restriction would be unnecessary.
You never need to write struct Highlight<'a, T: 'a>. Since Rust 1.31 the compiler infers that T must outlive 'a whenever the struct contains &'a T.
Independent lifetimes
One shared 'a can be too strict. Each reference that has a different relationship to the result should get its own lifetime parameter.
fn first_match<'a, 'b, T: PartialEq>(haystack: &'a [T], needle: &'b T) -> Option<&'a T> {
haystack.iter().find(|item| *item == needle)
}
fn main() {
let words = vec![
String::from("red"),
String::from("green"),
String::from("blue"),
];
let found;
{
let key = String::from("green");
found = first_match(&words, &key);
}
println!("{:?}", found);
}The result points into haystack, so only haystack is tied to the output. The needle is used only during the call. key is dropped at the end of the inner block, yet found is still usable afterwards. If both parameters shared 'a, the compiler would require found to stay within the region where key is alive, and the println! would fail with "key does not live long enough".
Lifetime elision with generics
Elision lets you leave out lifetimes in common cases. The rules apply only to lifetimes and never infer type parameters.
- Each elided lifetime in an input position becomes a fresh lifetime parameter.
- If there is exactly one input lifetime, it is assigned to every elided output lifetime.
- If one of the inputs is
&selfor&mut self, its lifetime is assigned to every elided output lifetime.
So fn head<T>(items: &[T]) -> &T compiles as written, because there is one input lifetime. longest above does not elide, because two inputs give no rule for the output. You must name 'a.
Bounds that mix type parameters and lifetimes
T: 'static
T: 'static is the most misread bound. It means "T contains no references shorter than 'static". It does not mean the value lives for the whole program. Owned types such as String and Vec<i32> satisfy it. A &String borrowed from a local variable does not.
use std::fmt::Debug;
use std::thread;
fn run_in_thread<T: Debug + Send + 'static>(value: T) {
thread::spawn(move || println!("{value:?}"))
.join()
.unwrap();
}
fn main() {
run_in_thread(String::from("owned"));
run_in_thread("a literal");
let local = String::from("borrowed");
// run_in_thread(&local); // error: `local` does not live long enough
println!("{local}");
}A string literal is a &'static str, so it is accepted. thread::spawn demands 'static because the new thread may outlive the function that created it.
T: 'a in function signatures
Struct definitions infer T: 'a, but trait objects have a default lifetime of 'static, and that default often forces an explicit bound.
use std::fmt::Display;
fn boxed<'a, T: Display + 'a>(value: T) -> Box<dyn Display + 'a> {
Box::new(value)
}
fn main() {
let name = String::from("Ferris");
let shown = boxed(&name);
println!("{shown}");
}Without + 'a on the dyn Display, the return type means Box<dyn Display + 'static>. The compiler would then require T: 'static, and boxed(&name) would fail. With the bound, the box is allowed to carry a borrow, and it is valid only while name is.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `lifetime may not live long enough` on a returned reference | The output is tied to the wrong input | Give the inputs separate lifetimes and tie only the right one to the output |
| `missing lifetime specifier` | Two or more input references and no `&self`, so elision cannot pick one | Declare `'a` and annotate the output |
| `the parameter type T may not live long enough` | `T` is stored behind a reference or trait object and the compiler cannot prove it outlives it | Add `T: 'a` |
| `borrowed value does not live long enough` when passing `&local` to a `T: 'static` function | `T` is a reference to a local | Pass an owned value, or clone it |
| `expected named lifetime parameter` in a struct field | A reference field has no lifetime | Add `<'a>` to the struct and annotate the field |
| Lifetimes appear after type parameters in angle brackets | Wrong order | Write `<'a, T>`, never `<T, 'a>` |
Design guidance
- Prefer owned data in generic structs when copying is cheap. A
Highlight<'a, T>that owns aVec<T>has no lifetime parameter and is easier to store and return. - Add a lifetime parameter only when you want to avoid copying, or when the data is large or cannot be cloned.
- Reach for a second lifetime only when a reference in the signature has a different relationship to the output than the others. Over-annotating with many lifetimes makes signatures harder to read without making them more permissive.
- When you see
T: 'staticin a library API, read it as "owned data only, no short-lived borrows".
Exercise
The function below is meant to return the longer of two slices, but the two inputs may come from different scopes. Explain why fn pick<'a, T>(a: &'a [T], b: &'a [T]) -> &'a [T] is more restrictive than needed when you only ever return a, and write the better signature.
Show answer
With a single 'a, the compiler treats the result as valid only for the overlap of both inputs, so a short-lived b limits how long the result can be used even though b is never returned. Only a needs to be tied to the output. The better signature is fn pick<'a, 'b, T>(a: &'a [T], b: &'b [T]) -> &'a [T]. The result then depends only on a, and b can be dropped before the result is used.
Exercise
Does String satisfy T: 'static? Does &String borrowed from a local variable? Why does std::thread::spawn need the bound?
Show answer
String satisfies T: 'static because it owns its data and holds no references. A &String borrowed from a local variable does not, because the borrow lasts only as long as the local. spawn needs the bound because the new thread can keep running after the spawning function returns, so the closure and everything it captures must not depend on borrows from that function's stack.