In Rust, why does passing a `&'static str` and a short-lived local borrow to `fn log_pair<'a>(key: &'a str, value: &'a str)` compile?
answer
- which region contains which
- outlives read as a subtype relation
- the reference type follows its lifetime
- 'a inferred at the call site
basics
~20 sBecause 'static outlives every 'a, &'static str is a subtype of &'a str, and &'a T is covariant in 'a. rustc infers 'a as the short region where the local borrow lives and shrinks the literal to it at the call.
solid answer
~40 sRust's subtyping is about lifetimes: `'long` is a subtype of `'short` when its region contains `'short`, and `'static` contains every region. Because `&'a T` is **covariant** in `'a`, that relation passes through the reference, so `&'static str` is a subtype of `&'a str` and may stand wherever the shorter type is expected. At the call, rustc infers one region for `'a` that both arguments satisfy - here the span where `&value` is live - and the literal is used at that shorter type. Nothing happens to `key` itself: a shared reference is `Copy`, the call receives a copy, and `key` is still `&'static str` afterwards. The annotation never lengthens anything; it only asks for references that live at least `'a`.
code
rust · 14 linesfn log_pair<'a>(key: &'a str, value: &'a str) -> usize {
println!("{key}={value}");
key.len() + value.len()
}
fn main() {
let key: &'static str = "region";
let n;
{
let value = String::from("eu-west");
n = log_pair(key, &value); // key shrinks from 'static to the local borrow
}
println!("{key} still usable, total {n}");
}go deeper
Recall that a longer-lived reference can be passed where a shorter one is expected, and that 'static outlives everything. Say plainly that annotations never extend a value's life.
Explain the call-site inference: rustc picks one region for 'a that every argument is a subtype of. Name covariance of &'a T in 'a as the reason the relation reaches the reference type.
Show where the easy rule stops: behind &mut or inside Cell the shrink is refused, and the resulting E0597 points at a 'static annotation rather than at variance itself.
Frame subtyping as what keeps lifetime-annotated APIs ergonomic: covariance lets callers mix data of different ages, and the invariant positions are the deliberate price of allowing writes.
## What subtyping means in Rust In Rust, **subtyping** means that a value of one type may be used where another type is expected, with no conversion and no code. The Rust Reference restricts it to exactly two cases: **variance with respect to lifetimes**, and the relation between **higher-ranked** types such as `for<'a> fn(&'a i32)` and their instantiations. If you erased every lifetime from a program, the only subtyping left would be type equality. There is no subtyping between two different structs, and turning a `Box<File>` into a `Box<dyn Read>` is an *unsizing coercion*, not subtyping. For lifetimes, the rule is about regions of code: - a **lifetime** in a type names a region of the program where a borrow must stay valid; - `'long` is a subtype of `'short` (written `'long: 'short` in a bound) when the region `'long` completely contains the region `'short`; - `'static` contains every region, so it is a subtype of every lifetime. The intuition is the one in the Rustonomicon: a reference that is valid for longer satisfies every requirement of one that only needs to be valid for less. ## Covariance: why the reference type follows its lifetime A lifetime relation alone is not enough; the compiler needs to know whether it carries over to the *type* that contains the lifetime. That property is **variance**. A type is **covariant** in a parameter when the parameter's subtyping passes straight through. `&'a T` is covariant in `'a` (and in `T`), so: 1. `'static` outlives `'a`; 2. therefore `&'static str` is a subtype of `&'a str`; 3. therefore a `&'static str` argument is accepted where `&'a str` is declared. | type | variance in `'a` | |---|---| | `&'a T` | covariant | | `&'a mut T` | covariant | | `Box<&'a str>`, `Vec<&'a str>` | covariant | | `Cell<&'a str>` | invariant | | `fn(&'a str)` | contravariant | The last two rows are where the easy story stops, and they are covered separately: a `&'static str` cannot be shrunk once it sits behind a `&mut` or inside a `Cell`. ## What rustc does at the call In `log_pair(key, &value)`, the signature demands that both arguments have the *same* type `&'a str`. rustc does not look for a lifetime that is literally equal to both; it looks for a region `'a` such that each argument is a **subtype** of `&'a str`. The local borrow `&value` is valid only until `value` is dropped, so `'a` can be at most that span. The literal is `&'static str`, a subtype of `&'a str` for any `'a`, so it fits as well. The call type-checks with `'a` set to the short region. The shortening applies to the argument, not to the variable. `key` is a shared reference, shared references are `Copy`, and the function receives a copy typed at the shorter lifetime. After the block that owns `value` ends, `key` can still be printed, returned or stored as a `&'static str`; the example below does exactly that. ## What this does not mean - It does not mean the local borrow is extended to `'static`. Lifetimes never make data live longer; `value` is still dropped at the end of its block. - It does not mean `'a` is a duration chosen by the function. The caller's borrows decide the region; the signature only states the relationship between them. - It does not mean any two references can be mixed. If the function stored the argument somewhere that outlives the call, the constraint would push `'a` up and the short borrow would fail with E0597. - It does not survive a `&mut`. Writing through `&mut &'static str` with a shorter `&str` would leave a dangling `'static` reference, so `&mut T` is invariant in `T` and this shortening is refused there. ## Why it matters in practice Lifetime subtyping is what makes everyday signatures usable. Without it, a function taking two `&'a str` parameters could only be called with references of identical lifetimes, and every string literal would clash with every borrowed `String`. Covariance lets callers mix long-lived and short-lived data freely, while invariance in the few places that allow writes keeps that freedom from opening a hole. The same rule is at work when a `Vec<&'static str>` of built-in names is passed to a function expecting `&[&'a str]` alongside a borrowed buffer, or when a `&'static` configuration value is stored in a struct whose lifetime is tied to a request: in each case rustc quietly uses the longer-lived data at the shorter type, and no annotation at the call site is needed.
- After the call, has `key` been downgraded to the shorter lifetime?No. `key` is a `&'static str`, shared references are `Copy`, and the call receives a copy used at the type `&'a str`. The variable's own type never changes, so `key` can still be returned, stored in a `'static` context or printed after the block that owned `value` has ended.
- Can one Rust struct be a subtype of another, the way a subclass is?No. The Rust Reference limits subtyping to lifetime variance and higher-ranked types; with lifetimes erased, only type equality remains. Using a concrete type as `dyn Trait` is an unsizing coercion and a `Deref` target is a deref coercion - both are conversions the compiler inserts, not subtyping.
- Does the same call still compile if the function takes `&mut &'a str` for the first argument?Not when the variable is annotated `&'static str`. `&mut T` is invariant in `T`, so `&mut &'static str` cannot become `&mut &'a str`; `'a` is forced to `'static`, and the short borrow is rejected with E0597, because the function could otherwise store it in the `'static` slot.
- Both arguments need identical lifetimes, so a literal and a local borrow cannot be mixed
- rustc extends the local borrow to 'static so that it matches the literal
- The 'a annotation makes the passed references live longer than they otherwise would
- Rust subtyping lets one struct type stand in for another, as inheritance does
- After the call the literal's variable is permanently downgraded to the short lifetime