Sub topic 10
Lifetimes next to type parameters
This chapter assumes you know basic generic functions, trait bounds, and the borrowing rules for &T. It shows how lifetime parameters and type parameters share one declaration list, and where they interact.
Two kinds of parameters, one list
Angle brackets after a function or type name can hold lifetime parameters, type parameters, and const parameters. Lifetimes come first, then types.
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"));
}'a says that both inputs and the returned reference are valid for the same region. The compiler picks the shorter of the two input lifetimes. T is chosen separately. Here T is str, so &'a T is &'a str.
?Sized relaxes the implicit Sized bound. Without it, T could not be str, because str has no size known at compile time. References to unsized types are fine, so the relaxation is safe here.
Lifetimes and type parameters are independent
A lifetime parameter never changes which concrete type is used. It only constrains how long references live. Monomorphization (the compiler generating one copy of the code per concrete type) ignores lifetimes. Lifetimes are erased after borrow checking, so they add no runtime cost and no extra copies.
Generic structs that hold references
A struct that stores a reference needs a lifetime parameter. If it is also generic, declare both.
use std::fmt::Debug;
struct Holder<'a, T> {
value: &'a T,
}
impl<'a, T: Debug> Holder<'a, T> {
fn new(value: &'a T) -> Self {
Holder { value }
}
fn show(&self) -> String {
format!("{:?}", self.value)
}
fn get(&self) -> &'a T {
self.value
}
}
fn main() {
let n = 42;
let h = Holder::new(&n);
println!("{}", h.show());
let r: &i32 = h.get();
println!("{}", r);
}Both parameters must be declared after impl and repeated on the type: impl<'a, T: Debug> Holder<'a, T>. The bound T: Debug sits on the impl block, so every method can use it.
Note that get returns &'a T, not &T tied to &self. That lets the caller keep the reference after the Holder is gone. If you wrote -> &T, elision would tie the result to &self and the result could not outlive the holder.
Outlives bounds
Sometimes a lifetime appears in a bound. T: 'a means that every reference inside T lives at least as long as 'a. For struct fields like &'a T, the compiler infers this bound, so you rarely write it.
flowchart TDThe most common explicit form is T: 'static. It does not mean the value lives forever. It means T contains no borrowed data except 'static borrows. An owned String satisfies T: 'static, and a &str borrowed from a local String does not. You will meet this bound on thread spawning and boxed trait objects.
Common errors
- Writing
Holder<T>instead ofHolder<'_, T>orHolder<'a, T>in a signature. Eliding the lifetime in a path is allowed but discouraged, and the'_form makes the hidden borrow visible. - Putting the type parameter before the lifetime, as in
<T, 'a>. This is a compile error. - Returning a reference tied to the wrong input. The fix is to name the lifetime on the input you actually return from.
Exercise
In fn pick<'a, 'b, T>(a: &'a T, b: &'b T) -> &'a T, which argument may the returned reference come from, and why does the order 'a, 'b, T matter?
Show answer
The result may only come from a, because only a has lifetime 'a. Returning b would not compile, since 'b is not known to outlive 'a. The order matters because the language requires lifetime parameters to be listed before type parameters.