BorrowCheck › Rust language core
Lifetimes, subtyping, variance
Annotations and elision, 'static, subtyping via substitutability, the three kinds of variance, HRTB.
The topic explains lifetimes: an annotation such as 'a does not extend how long a value lives; it describes a relation between references that the compiler checks. The questions check when an annotation is required (a reference in a struct field, a reference returned from a function), what the bound T: 'a demands, and when a function can be written without annotations thanks to lifetime elision. The subtopic on 'static separates 'static as a reference lifetime from the bound T: 'static and covers &'static str, the F: 'static requirement of thread::spawn, the implicit + 'static on Box<dyn Trait>, Box::leak and constant promotion. The subtopics on subtyping and variance show why &'static str is accepted where &'a str is expected, how covariance differs from contravariance and invariance, why &mut T is invariant over T, and how a struct's variance follows from its fields and from PhantomData. The last subtopic is about higher-ranked trait bounds (HRTB): the meaning of for<'a> in a bound, the Fn(&T) -> &U form, and cases where a closure returning a reference fails to compile without an explicit bound.
38 questions: 16 basic, 17 intermediate, 5 advanced. 6 info pages, 16 sources.
Subtopics
- Lifetime annotations and syntax
- Elision rules
'static: type vs bound- Subtyping and substitutability
- Variance: co-, contra-, invariance
- Higher-ranked trait bounds
Previous: Borrowing, references, NLL · Next: Structs, enums, pattern matching