rust-syntax-lifetimes
Installation
SKILL.md
rust-syntax-lifetimes
Lifetimes are compile-time-only annotations describing the validity scope of references. The compiler ALWAYS infers lifetimes for local variables; explicit annotations are required ONLY where the borrow checker cannot deduce relationships between input and output references on function and type signatures. This skill covers when annotation is required, how elision works, the two distinct meanings of 'static, HRTB, variance, and the edition-2024 RPIT capture change.
Quick Reference
Core rules (deterministic)
- ALWAYS rely on lifetime elision in function signatures when it applies. NEVER write
<'a>if the three elision rules already infer the same signature (Clippy lintneedless_lifetimes). - NEVER use
T: 'staticwhen a generic'awould suffice. The'staticbound overconstrains callers and is one of the most common over-annotation mistakes. - NEVER confuse
&'static T(a reference that lives the whole program) withT: 'static(a bound saying the value contains no non-'staticborrows; owned types satisfy it). - ALWAYS treat
&mut Tas invariant inT. NEVER assume it is covariant; passing&mut Vec<&'static str>where&mut Vec<&'a str>is expected is rejected because of invariance. - ALWAYS add
+ use<'a, T>to an RPIT in edition 2024 when you want to NOT capture a generic; the 2024 default is to capture all in-scope generics, the inverse of pre-2024 behaviour.
Three elision rules (function signatures only)
Per https://doc.rust-lang.org/reference/lifetime-elision.html: