Variance and subtyping
Quick answer
Variance determines whether a lifetime relationship can be carried through a containing type. It matters when a borrowed value must fit into a shorter-lived context.
Read-only versus writable positions
If 'long: 'short, a shared reference with lifetime 'long can be used as one with lifetime 'short. &'a T is covariant in its lifetime and T; &'a mut T is covariant in its lifetime but invariant in T, preventing replacement of a long-lived inner reference with a short-lived one. Function argument types are contravariant. These are type relationships, not changes to runtime lifetime.
fn choose<'a>(_: &'a String, text: &'static str) -> &'a str { text }fn main() { let local = String::from("local"); println!("{}", choose(&local, "fixed"));}Expected stdout (not executed):
fixedThe return type uses the shorter lifetime chosen by the caller.
fn replace<'a>(slot: &mut &'a str, value: &'a str) { *slot = value; }fn main() { let mut slot: &'static str = "fixed"; { let local = String::from("short"); replace(&mut slot, &local); } println!("{slot}");}Expected: compilation fails; exact diagnostic not verified.
The writable slot must never contain a dangling reference.
Common mistake
Do not confuse invariance in T with invariance in the outer lifetime of &mut T.
Try it yourself
Explain why replacing the mutable slot with a shared reference removes the write operation.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Variance and subtyping — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
Can a mutable reference to a slot holding a long-lived reference be treated as a slot accepting any shorter reference?
Variance and subtyping — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn choose<'a>(_: &'a String, text: &'static str) -> &'a str { text } fn main() { let local = String::from("local"); println!("{}", choose(&local, "fixed")); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Variance and subtyping — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn replace<'a>(slot: &mut &'a str, value: &'a str) { *slot = value; } fn main() { let mut slot: &'static str = "fixed"; { let local = String::from("short"); replace(&mut slot, &local); } println!("{slot}"); } ``` Which outcome or interpretation best matches this example?