Sub topic 2
Lifetime subtyping: when a longer lifetime can stand in for a shorter one
This chapter assumes you can read basic lifetime annotations on functions and structs, and that you know generics and trait bounds. You don't need to know variance yet. The next chapters build on this one.
The outlives relation, briefly
A lifetime names a region of the program during which a reference is valid. When you write 'long: 'short, you say that 'long outlives 'short. Every point in 'short is also in 'long. Read the colon as "lasts at least as long as".
'static outlives every other lifetime, so 'static: 'a holds for any 'a.
What lifetime subtyping says
Rust uses the outlives relation to define subtyping between lifetimes. If 'long: 'short, then 'long is a subtype of 'short, written 'long <: 'short. A value of a subtype can be used wherever the supertype is expected.
This can feel backwards. The longer lifetime is the subtype because it is the more specific promise. A reference valid for ten minutes also satisfies "valid for at least five minutes". The reverse is false.
So a &'long str can be used where a &'short str is expected. The compiler converts it silently. There is no cast and no syntax for it.
| You have | You need | Allowed? |
|---|---|---|
| `&'long T` | `&'short T` | Yes, the lifetime shrinks |
| `&'short T` | `&'long T` | No, the reference might dangle |
| `&'static T` | `&'a T` for any `'a` | Yes |
Subtyping in a real function
Here is the first example from this tutorial's plan.
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let outer = String::from("lives longer");
{
let inner = String::from("short");
let r = longest(&outer, &inner);
println!("{r}");
}
}The signature demands one lifetime 'a shared by both arguments. But &outer and &inner have different regions, because inner dies first.
The compiler resolves this with subtyping. It picks 'a to be the region of the inner block. The borrow of outer is valid for longer than that, so it is a subtype of &'a str. It is shrunk to fit. Both arguments then match, and the result r is valid inside the block, which is the only place it is used.
Nothing here changes how long outer lives. Shrinking a reference's lifetime only means the compiler stops relying on the extra time.
Writing the relation yourself
You can state outlives relations in generics. Both forms below mean the same thing.
fn pick_second<'a, 'b: 'a>(_first: &'a str, second: &'b str) -> &'a str {
second
}
fn pick_second_where<'a, 'b>(_first: &'a str, second: &'b str) -> &'a str
where
'b: 'a,
{
second
}
fn main() {
let outer = String::from("outer");
{
let inner = String::from("inner");
println!("{}", pick_second(&inner, &outer));
println!("{}", pick_second_where(&inner, &outer));
}
}The bound 'b: 'a tells the compiler that second lives at least as long as 'a. That is what allows second to be returned as a &'a str. Subtyping performs the shrink, and the bound proves it is legal.
Remove the bound and the function no longer compiles:
// Does not compile: the compiler cannot prove 'b outlives 'a.
fn pick_second_bad<'a, 'b>(_first: &'a str, second: &'b str) -> &'a str {
second
}The error reads "lifetime may not live long enough". It usually suggests adding 'b: 'a. This is the most common subtyping error you will meet, and the fix is to state the relation.
Why `'static` is the bottom of the chain
Because 'static: 'a for every 'a, a &'static str fits any reference slot.
fn shrink<'short>(s: &'static str) -> &'short str {
s
}
fn main() {
let text: &'static str = "string literal";
let local = String::from("local data");
let shorter = shrink(text);
println!("{shorter} {local}");
}The opposite direction is rejected. A function that turns an arbitrary &'a str into a &'static str would let a dangling reference escape.
// Does not compile: 'a is not known to outlive 'static.
fn grow<'a>(s: &'a str) -> &'static str {
s
}Where subtyping happens
Subtyping is not a conversion you request. The compiler applies it wherever it checks that a value's type matches an expected type: function arguments, let bindings with annotations, return values, and struct fields. At each of these sites it may shrink a lifetime.
You never see this directly. You see its effects in two ways:
- Code that looks like it should fail to compile succeeds, as in
longestabove. - A borrow check error complains that some lifetime "must outlive" another.
Rust also does not infer a single lifetime for a variable and then freeze it. The compiler collects a set of outlives constraints, such as "this region must outlive that one", and solves for the smallest regions that satisfy all of them. An error means the constraints cannot be satisfied.
What subtyping does not cover
Lifetimes are the only place where Rust has subtyping in the usual sense. There is no class inheritance. A String is not a subtype of &str, and a type implementing a trait is not a subtype of the trait. Those conversions are coercions or trait impls.
Subtyping also does not automatically extend to types that contain lifetimes. Whether Wrapper<'long> can stand in for Wrapper<'short> depends on how Wrapper uses 'a. That property is called variance. For &'a T, the answer is yes, as in the tables above. For other types it can be no. The next chapters cover the cases.
Common mistakes
- Reading the direction backwards.
'long <: 'shortmeans'longcan be used where'shortis expected. The subtype is the lifetime that lasts longer. - Fixing errors with
'static. Adding'staticto make a "lifetime may not live long enough" error go away usually demands more than the data can give. Prefer an outlives bound like'b: 'a, which asks only for what you need. - Thinking subtyping extends a lifetime. Subtyping only lets the compiler treat a long borrow as a short one. It never makes data live longer.
- Using a single
'awhen two are clearer. With one shared'a, the compiler shrinks both inputs to the shorter region. That is fine forlongest. If the output only comes from one input, give that input its own lifetime so callers are not restricted by the other.
Exercise
The function below does not compile. Explain why, then add the smallest change to the signature that makes it compile. fn firstof<'a, 'b>(a: &'a str, b: &'b str) -> &'b str { a }
Show answer
The function returns a, which has type &'a str, where a &'b str is required. That is only valid if 'a outlives 'b, because a longer lifetime may shrink to a shorter one but not the other way around. The compiler cannot prove this, so it reports "lifetime may not live long enough". Adding the bound 'a: 'b, either as <'a: 'b, 'b> or in a where clause, makes it compile. The shrink from &'a str to &'b str is then a legal subtyping step.
Exercise
In let r = longest(&outer, &inner); from the chapter, outer is declared before the block and inner inside it. Which of the two borrows is shrunk to reach the lifetime 'a, and what would happen if r were printed after the closing brace of the block?
Show answer
The borrow of outer is shrunk, because it is the longer one. 'a is chosen as the region of the inner block, and &outer is a subtype of &'a str. If r were used after the block, 'a would have to extend past the point where inner is dropped. No such region exists, so the compiler would report that inner does not live long enough.