In Rust, why can a `Hook<'s>` holding `fn(&'s str)` be passed where `Hook<'static>` is expected, but not once the field becomes `fn(&'s str) -> &'s str`?
answer
- who supplies the argument
- a function that accepts more is safer
- the only contravariant position
- co- and contravariant uses together
basics
~20 sfn(T) is contravariant in its argument: a callback that accepts any &'s str also accepts every &'static str, so Hook<'s> is a subtype of Hook<'static>. Returning &'s str adds a covariant use, and mixed uses make Hook invariant.
solid answer
~40 sFunction-pointer arguments are the one **contravariant** position in Rust: since `&'static str` is a subtype of `&'s str`, `fn(&'s str)` is a subtype of `fn(&'static str)` - a callback that can handle short-lived strings can certainly handle `'static` ones. A struct whose only use of `'s` is that argument inherits the contravariance, so `Hook<'s>` may be passed to `run_static(hook: Hook<'static>)`. Changing the field to `fn(&'s str) -> &'s str` adds a covariant use in the return type; one parameter used both ways is **invariant**, and rustc 1.99.1 rejects the same call with E0521, noting "the struct `Hook<'a>` is invariant over the parameter `'a`". The opposite direction, `Hook<'static>` to `Hook<'s>`, never worked for the original field.
code
rust · 20 linesstruct Hook<'a> {
on_line: fn(&'a str),
}
fn print_line(line: &str) {
println!("got {line}");
}
fn run_static(hook: Hook<'static>) {
(hook.on_line)("boot complete");
}
fn forward<'s>(hook: Hook<'s>) {
run_static(hook); // Hook<'s> is a subtype of Hook<'static>
}
fn main() {
let hook: Hook<'_> = Hook { on_line: print_line };
forward(hook);
}go deeper
Recall that a function which accepts any short-lived string can also be handed long-lived ones, so it is the more flexible callback.
Explain that function arguments are Rust's only contravariant position, while return types stay covariant, and how a struct inherits that from its fields.
Show that a lifetime in both argument and return makes the wrapper invariant, read the E0521 notes, and separate contravariance from higher-ranked subtyping of plain functions.
Weigh lifetime-parameterised callback wrappers against higher-ranked fn(&str) or dyn Fn(&str) fields; the former leak variance into the public API and constrain every caller.
## Function arguments are the contravariant position Variance asks whether a subtype relation on a parameter carries over to the type built from it. For most Rust types it carries over unchanged (**covariance**) or not at all (**invariance**). Function-pointer arguments are the exception: there it carries over **reversed**, which is **contravariance**. The Rustonomicon calls function arguments the only source of contravariance in the language. The argument is about who supplies the value: - `&'static str` is a subtype of `&'s str`, because `'static` outlives `'s`; - a function of type `fn(&'s str)` promises to accept any string valid for at least `'s`; - every `&'static str` meets that promise, so the function can be used wherever an `fn(&'static str)` is wanted; - therefore `fn(&'s str)` is a subtype of `fn(&'static str)` - the direction is flipped relative to the argument types. The return type behaves normally: `fn() -> &'static str` is a subtype of `fn() -> &'s str`, because a caller expecting a short-lived result is happy with a long-lived one. ## The wrapper as first written `struct Hook<'a> { on_line: fn(&'a str) }` uses `'a` only in an argument position, so the struct is contravariant in `'a`. That makes this compile with rustc 1.99.1: ```rust fn run_static(hook: Hook<'static>) { (hook.on_line)("boot complete"); } fn forward<'s>(hook: Hook<'s>) { run_static(hook); } ``` `forward` receives a hook that can handle any `&'s str` and hands it to code that will only ever give it `&'static str` - always safe. The reverse, `fn shorten<'s>(h: Hook<'static>) -> Hook<'s> { h }`, is rejected with "lifetime may not live long enough": a hook that requires `'static` input cannot be offered to callers who might pass a short-lived string, because it might keep the string somewhere global. ## What the return type changes Change the field to `fn(&'a str) -> &'a str`. Now `'a` appears twice: contravariantly in the argument and covariantly in the return. The struct-level rule is that a parameter used in positions of different variance is **invariant**. `forward` no longer compiles; rustc 1.99.1 reports `error[E0521]: borrowed data escapes outside of function` with two telling notes: 1. "requirement occurs because of the type `Hook<'static>`, which makes the generic argument `'static` invariant"; 2. "the struct `Hook<'a>` is invariant over the parameter `'a`". The reason is concrete: a `Hook<'s>` may return the `&'s str` it was given, and code expecting a `Hook<'static>` would treat that result as `'static`. | field type | variance of `Hook<'a>` in `'a` | |---|---| | `fn(&'a str)` | contravariant | | `fn() -> &'a str` | covariant | | `fn(&'a str) -> &'a str` | invariant | | `fn(&str)` (no `'a`) | not allowed - E0392, `'a` unused | ## Why it rarely bites Ordinary function items and closures are written with elided lifetimes: `fn print_line(line: &str)` really has the higher-ranked type `for<'x> fn(&'x str)`, which is a subtype of `fn(&'a str)` for *every* `'a` through higher-ranked subtyping, not through contravariance. That is why `Hook { on_line: print_line }` fits a `Hook` of any lifetime. Contravariance only becomes visible when a type names one *specific* lifetime in an argument position, as `Hook<'a>` does - typically a callback wrapper, a visitor or a parser hook tied to one input buffer. ## Takeaways for API design - A callback field that only *consumes* `&'a T` makes the wrapper contravariant; callers can pass a wrapper for a shorter lifetime where a longer one is required, not the reverse. - Adding a return that mentions the same lifetime silently makes the wrapper invariant and can break existing callers with E0521 or E0597. - A boxed closure does not behave like a fn pointer here. The Reference lists `dyn Trait<T> + 'a` as invariant in `T`, so `struct H<'a> { f: Box<dyn Fn(&'a str)> }` is invariant in `'a`; rustc 1.99.1 rejects converting `H<'s>` to `H<'static>` with a note that the struct is invariant over `'a`. - When the callback should accept any lifetime, store `fn(&str)` or `Box<dyn Fn(&str)>` without a struct lifetime, and let higher-ranked types do the work.
- Can a `Hook<'static>` (field `fn(&'static str)`) be passed where `Hook<'s>` is expected?No. Contravariance runs the other way: only `Hook<'s>` to `Hook<'static>` is allowed. A hook that demands `'static` input might store its argument globally, so offering it to callers with short-lived strings would be unsound; rustc 1.99.1 rejects `fn shorten<'s>(h: Hook<'static>) -> Hook<'s> { h }` with "lifetime may not live long enough".
- Why does `Hook { on_line: print_line }` fit a `Hook` of any lifetime when `print_line(line: &str)` names none?`print_line` has the higher-ranked type `for<'x> fn(&'x str)`. The Reference lists higher-ranked function pointers as their own subtyping case: such a type is a subtype of every instantiation, `fn(&'a str)` for any `'a`. That substitution, not contravariance, is what makes plain functions fit; contravariance only shows once a struct fixes one lifetime.
A phone charger rated for any input from 100 to 240 volts can replace one that only accepts 230 volts, but not the other way round: for something that takes input, accepting more makes it the more widely usable part. A callback that accepts strings of any lifetime from 's up can likewise stand in where one taking only 'static strings is required.
- fn(&'a str) is covariant in 'a, like the reference it takes
- Function pointers have no lifetimes, so variance never applies to them
- When a parameter is used in both an argument and a return, the argument use wins
- Hook<'static> can always be passed where Hook<'s> is expected, since 'static is longer
- Plain functions fit any Hook lifetime because of contravariance alone