Sub topic 2
Contravariance, Variance Inference, and Higher-Ranked Bounds
Assume ownership, borrowing, lifetime annotations, generics, and the Fn traits.
Contravariance: function arguments run the other way
If 'long: 'short, a reference with 'long can be used where a reference with 'short is expected. Shared references are covariant in their lifetime.
Function argument types are contravariant. A function that accepts a shorter-lived reference is more flexible because it can accept references with either lifetime:
fn call(f: fn(&str) -> usize) -> usize {
f("hello")
}
fn length(s: &str) -> usize {
s.len()
}
fn main() {
println!("{}", call(length));
}Function return types are covariant. Therefore, function types combine contravariant argument positions with covariant return positions.
How the compiler computes variance
The compiler examines where each generic parameter appears:
&'a Tis covariant in'aandT.&'a mut Tis covariant in'abut invariant inT.Cell<T>is invariant inT.fn(T) -> Uis contravariant inTand covariant inU.
A parameter used in both conflicting directions becomes invariant. Invariance means the compiler cannot substitute either a longer or shorter lifetime.
PhantomData: choosing the variance you want
PhantomData<T> records a type relationship without storing a value of type T. Its argument affects variance:
use std::cell::Cell;
use std::marker::PhantomData;
struct Co<'a>(PhantomData<&'a ()>);
struct Inv<'a>(PhantomData<Cell<&'a ()>>);
fn shorten<'long: 'short, 'short>(x: Co<'long>) -> Co<'short> {
x
}Co is covariant. Inv is invariant because Cell is invariant.
Why a fixed lifetime parameter is not enough
A bound such as Fn(&'a str) -> &'a str uses one particular 'a chosen for the surrounding call. It cannot express that the function works independently for every lifetime.
Reading and writing `for<'a>`
A higher-ranked trait bound quantifies over all lifetimes:
fn apply_to_both<F>(f: F) -> (usize, usize)
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let owned = String::from(" text ");
(f(&owned).len(), f(" literal ").len())
}
fn main() {
println!("{:?}", apply_to_both(|s| s.trim()));
}Read for<'a> Fn(&'a str) -> &'a str as “F implements this function trait for every possible 'a.” In many Fn bounds, Fn(&str) -> &str is elided shorthand for this relationship.
Exercise
Why is a function argument position contravariant?
Show answer
A function that accepts shorter-lived references can also accept longer-lived references, so it is more general.