Sub topic 6
Contravariance: function arguments run the other way
This chapter assumes you know what covariance and invariance mean for lifetimes, and that 'long: 'short means 'long outlives 'short. It also assumes you can read function pointer types such as fn(&str) -> usize.
The direction flips
For covariant types, a longer lifetime can stand in for a shorter one. &'static str works wherever &'a str is expected, because 'static outlives every 'a. The subtyping arrow points the same way before and after wrapping the lifetime in &.
Contravariance reverses the arrow. If 'long: 'short, then 'long is a subtype of 'short. For a contravariant type F, the relation becomes F<'short> is a subtype of F<'long>. The shorter lifetime sits in the subtype position.
In Rust, contravariance appears in one place: the argument position of a function pointer. For fn(A) -> R:
- It is contravariant in
A. - It is covariant in
R.
Why the direction flips
Think about what a caller needs from a function that takes a &'static str. The caller promises to pass a string that lives forever. A function that accepts any &'a str, including short-lived ones, can handle that promise without trouble. It asks for less than the caller offers.
So a function that accepts shorter lifetimes can replace a function that demands longer ones. The more general consumer is the subtype, and the lifetime in its argument is the shorter one.
The next code shows this with a struct that stores a function pointer.
struct Handler<'a> {
callback: fn(&'a str) -> usize,
}
fn widen<'long: 'short, 'short>(h: Handler<'short>) -> Handler<'long> {
h
}
fn count(s: &str) -> usize {
s.len()
}
fn main() {
let h = Handler { callback: count };
let w: Handler<'static> = widen(h);
println!("{}", (w.callback)("static text"));
}widen turns a Handler<'short> into a Handler<'long>, where 'long is the longer lifetime. Under covariance that would be rejected. It compiles here because Handler<'a> is contravariant in 'a. A handler that tolerates short-lived strings also tolerates long-lived ones.
The unsound direction is rejected
Now try the covariant direction, which is the reverse of widen.
struct Handler<'a> {
callback: fn(&'a str) -> usize,
}
// Does not compile: Handler<'a> is contravariant in 'a, not covariant.
// fn shrink<'long: 'short, 'short>(h: Handler<'long>) -> Handler<'short> {
// h
// }The compiler must refuse this. A fn(&'static str) is allowed to keep the string forever. The next program shows such a function.
use std::sync::Mutex;
static SEEN: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());
fn remember(s: &'static str) -> usize {
SEEN.lock().unwrap().push(s);
s.len()
}
fn main() {
let f: fn(&'static str) -> usize = remember;
println!("{}", f("a literal"));
let local = String::from("temporary");
// Does not compile: fn(&'static str) is not usable as fn(&str).
// let g: fn(&str) -> usize = f;
// g(&local);
println!("{}", local.len());
}If g were allowed, remember would push a reference to local into a static vector. After local is dropped, that vector would hold a dangling pointer. Rejecting the shrink keeps remember limited to arguments that really live forever.
Variance of common types
The table summarizes the positions you will meet. "Position" means where the lifetime or type appears inside the type.
| Type | Variance in `'a` | Variance in `T` |
|---|---|---|
| `&'a T` | covariant | covariant |
| `&'a mut T` | covariant | invariant |
| `Cell<T>`, `RefCell<T>` | n/a | invariant |
| `*const T` | n/a | covariant |
| `*mut T` | n/a | invariant |
| `fn(T) -> U` | n/a | contravariant in `T`, covariant in `U` |
| `dyn Trait<T> + 'a` | covariant | invariant |
The last row has an important consequence. Box<dyn Fn(&'a str)> is a trait object, and trait object parameters are invariant. A boxed closure type does not get the contravariance of a bare fn pointer.
Combining positions
Variance composes by multiplication. A covariant position inside a covariant position stays covariant. Anything that crosses a contravariant position flips.
fn(&'a str)is contravariant in'a.fn(fn(&'a str))is covariant in'a. The inner function flips the direction once, and the outer function flips it again.fn(&'a str) -> &'a stris invariant in'a. The argument position demands contravariance and the return position demands covariance. Nothing satisfies both, so the compiler picks invariance.
The last case catches people who define a struct with a fn(&'a str) -> &'a str field and then wonder why the lifetime cannot shrink. The fix is usually to make the function higher-ranked, which removes 'a from the struct. The chapters on for<'a> explain how.
struct Transform<'a> {
f: fn(&'a str) -> &'a str,
}
fn identity(s: &str) -> &str {
s
}
fn main() {
let t = Transform { f: identity };
let text = String::from("kept");
// Transform<'a> is invariant in 'a, so 'a is fixed at one lifetime.
println!("{}", (t.f)(&text));
}This code compiles because one fixed 'a is enough here. Trouble only starts when you need the struct at two different lifetimes.
Common mistakes
- Expecting closures to behave like
fnpointers. A generic parameterF: Fn(&'a str)is a bound, not a type with a variance. Variance only applies to concrete types such asfnpointers, structs, and trait objects. - Expecting a struct to shrink. If a struct holds a
fn(&'a T) -> &'a T, or anything mixing argument and return positions, it is invariant in'a. - Reading errors backwards. When a lifetime error mentions a function argument, ask which direction of conversion the compiler tried. Contravariant positions accept the shorter-lived side of a pair, and the error often shows the opposite.
Exercises
Exercise
A struct S<'a> has one field, f: fn(&'a str). Can you convert an S<'static> into an S<'short> for a shorter 'short? Can you convert an S<'short> into an S<'static>?
Show answer
Only the second conversion is allowed. fn(&'a str) is contravariant in 'a, so S<'short> can be used where S<'static> is expected. The first conversion is rejected, because a fn(&'static str) may store its argument for the whole program.
Exercise
What is the variance of fn(fn(&'a str)) in 'a, and why?
Show answer
Covariant. The inner fn(&'a str) is contravariant in 'a. Putting it in the argument position of the outer function flips the direction a second time, and two flips cancel.
Exercise
A struct has the field f: fn(&'a str) -> &'a str. Why can 'a not be shrunk or widened, and what is the variance?
Show answer
The argument position is contravariant in 'a and the return position is covariant in 'a. A single lifetime cannot move in both directions, so the struct is invariant in 'a.