Sub topic 14
Higher-ranked types and subtyping
This chapter assumes you have read the earlier chapters on lifetime subtyping, contravariance, and the for<'a> syntax. You should know that 'long: 'short means 'long outlives 'short, and that a longer lifetime can stand in for a shorter one. Here we apply those ideas to types that contain a for<'a> binder.
A higher-ranked type is a type, not just a bound
Most for<'a> examples appear in where clauses, so it is easy to think of the binder as syntax for bounds only. It also appears inside types. A function pointer that accepts a reference of any lifetime has this type:
for<'a> fn(&'a str) -> usizeYou almost never write the binder out. Lifetime elision writes it for you:
fn(&str) -> usizeBoth spellings mean the same thing. The function promises to work for every lifetime 'a the caller picks. This differs from a type with a specific lifetime:
fn(&'static str) -> usizeThis function pointer is only promised to work when given a 'static string. The first type makes a stronger promise than the second. Subtyping is how the compiler uses that fact.
The rule: a higher-ranked type is a subtype of its instantiations
A type with a for<'a> binder is a subtype of the same type with 'a replaced by any particular lifetime. Written informally:
for<'a> fn(&'a str) -> usize <: fn(&'x str) -> usize // for any 'xThe reasoning is practical. If a function works for every lifetime, it works for the one lifetime 'x you need. You can use it anywhere that expects a function for 'x.
The reverse does not hold. A function that works for 'static only has not promised to work for the short borrow of a local variable.
fn takes_static(f: fn(&'static str) -> usize) -> usize {
f("static")
}
fn static_len(s: &'static str) -> usize {
s.len()
}
fn len_of(s: &str) -> usize {
s.len()
}
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
// `len_of` has type `for<'a> fn(&'a str) -> usize`.
// It is accepted where `fn(&'static str) -> usize` is expected.
println!("{}", takes_static(len_of));
println!("{}", takes_static(static_len));
// The output lifetime is tied to the input lifetime, so
// instantiating 'a = 'static gives fn(&'static str) -> &'static str.
let f: fn(&'static str) -> &'static str = first_word;
println!("{}", f("hello world"));
}len_of is accepted by takes_static through exactly this subtyping step. The compiler instantiates the binder with 'static and finds an exact match.
Now try the reverse direction.
fn takes_any(f: for<'a> fn(&'a str) -> usize) -> usize {
let owned = String::from("temporary");
f(&owned) // `owned` has a short, local lifetime
}
fn static_len(s: &'static str) -> usize {
s.len()
}
fn len_of(s: &str) -> usize {
s.len()
}
fn main() {
println!("{}", takes_any(len_of));
// println!("{}", takes_any(static_len));
// error: mismatched types
// expected fn pointer `for<'a> fn(&'a str) -> usize`
// found fn item `fn(&'static str) -> usize {static_len}`
}Inside takes_any, the call f(&owned) borrows a local String. That is only sound if f accepts any lifetime. static_len does not, so the compiler rejects it.
How this connects to contravariance
There are two ways to reach the same conclusion, and they agree.
The first is contravariance. A function pointer fn(T) -> U is contravariant in T. Because &'static str is a subtype of &'short str, the direction flips for functions:
fn(&'short str) -> usize <: fn(&'static str) -> usizeA function that handles short-lived references can certainly handle 'static ones.
The second is the binder itself. Instantiating for<'a> with 'static gives fn(&'static str) -> usize directly.
The binder goes further than contravariance. Contravariance relates two types that each have a fixed lifetime. The binder says the function is simultaneously valid for all lifetimes, so it is a subtype of every one of those fixed-lifetime types. In effect it is the bottom of that family.
| Type | Works for | Can be passed where `fn(&'static str) -> usize` is expected? | Can be passed where `for<'a> fn(&'a str) -> usize` is expected? |
|---|---|---|---|
| `for<'a> fn(&'a str) -> usize` | every lifetime | Yes | Yes |
| `fn(&'x str) -> usize` for one fixed `'x` shorter than `'static` | `'x` and anything outliving it | Yes, by contravariance | No |
| `fn(&'static str) -> usize` | `'static` only | Yes | No |
Where the rule is applied
Subtyping on higher-ranked types is applied at coercion sites, where the compiler already checks that a value matches an expected type. These include function arguments, let bindings with a type annotation, and struct fields. The compiler does it by replacing the bound lifetime with an inference variable, the same way it handles a generic function call, and then solving the constraints.
The reverse direction needs a different step. To check fn(&'static str) -> usize against for<'a> fn(&'a str) -> usize, the compiler would have to prove the function works for an arbitrary 'a that it treats as a fresh, unknown lifetime. A function that only works for 'static cannot satisfy that, so the check fails.
A function item such as len_of is not a function pointer. It has its own zero-sized type, and that type implements for<'a> Fn(&'a str) -> usize. Subtyping applies after the item is coerced to a pointer, or when the compiler checks the Fn bound.
Gotchas
- Trait impls do not follow subtyping. When the compiler looks for a trait impl,
for<'a> fn(&'a str)andfn(&'static str)are treated as different types. If you implement a trait for one of them, a value of the other may not match, even though a coercion would be legal. Lifetime-only differences between higher-ranked types have caused long-standing coherence edge cases in the compiler. Avoid writing trait impls that depend on them. - Annotating the wrong side. Writing
fn(&'static str)where you meantfn(&str)makes the type less general. Callers must then pass'staticdata, or the function can only be used with'staticdata. Prefer elision unless you need a specific lifetime. - Binder placement matters.
for<'a> fn(&'a str) -> &'a stris not the same asfn(&'a str) -> &'a strwith'adeclared on the enclosing function. The first lets the caller of the pointer choose'aon each call. The second fixes'aonce, when the outer function is called.
Summary of the rules
- A
for<'a>binder means "for every lifetime'a", chosen by whoever uses the value. - A higher-ranked type is a subtype of each of its instantiations.
- An instantiation is never a subtype of the higher-ranked type, unless it can be shown to hold for all lifetimes.
- Subtyping happens at coercion sites and in bound checking. It does not change which trait impl is selected.
Exercise
Given fn shorten(s: &str) -> &str { s }, does let f: fn(&'static str) -> &'static str = shorten; compile? Does let g: for<'a> fn(&'a str) -> &'static str = shorten; compile? Explain each.
Show answer
The first compiles. shorten has type for<'a> fn(&'a str) -> &'a str. Instantiating 'a = 'static gives fn(&'static str) -> &'static str, which is the annotated type. The second does not compile. It requires the return value to be 'static for every input lifetime, but shorten returns a reference with the same lifetime as its input. For a short input borrow the result is only that short, so it does not satisfy the 'static return type.
Exercise
A function fn call(f: for<'a> fn(&'a u8) -> u8) -> u8 is given a function pointer of type fn(&'static u8) -> u8. Why is this rejected, and which change to the pointer's type would make it accepted?
Show answer
call requires a function that accepts a reference of any lifetime, because it may call f with a short-lived borrow of a local. A fn(&'static u8) -> u8 pointer only promises to work for 'static references, so it is not a subtype of the higher-ranked type. Changing the parameter to an elided lifetime, fn(&u8) -> u8, which means for<'a> fn(&'a u8) -> u8, makes the pointer acceptable.