Which Rust version and edition introduced each lifetime feature (so a suggestion matches the project's MSRV), the lints that catch lifetime noise, and how to keep lifetime-related API guarantees under test.
Contents
- Lifetime features by Rust version
- Edition differences
- Error codes that changed over time
- Lints
- Testing lifetime guarantees
- CI with the scripts
Lifetime features by Rust version
| Rust | Feature | Use instead before it |
|---|---|---|
| 1.0 | elision rules, 'static, T: 'a, HRTB for<'a>, PhantomData | |
| 1.26 | impl Trait in argument and return position | Box<dyn Trait>, named generics |
| 1.31 (edition 2018) | NLL; anonymous lifetime '_; impl-header elision (impl Display for T<'_>); inferred T: 'a on struct fields | named lifetimes everywhere; explicit where T: 'a |
| 1.36 | NLL on edition 2015 | |
| 1.39 | async fn / .await | futures 0.1 combinators |
| 1.63 | std::thread::scope; old borrow checker removed | crossbeam::scope, Arc |
| 1.65 | generic associated types (type Item<'a> where Self: 'a) | lending-iterator crates, boxing |
| 1.70 | OnceCell, OnceLock | once_cell, lazy_static |
| 1.75 | async fn and -> impl Trait in traits (RPITIT) | async-trait (boxes), associated future types |
| 1.80 | LazyCell, LazyLock | once_cell::sync::Lazy |
| 1.82 | precise capturing -> impl Trait + use<'a, T> | the Captures<'a> trait trick, + 'a |
| 1.85 (edition 2024) | RPIT captures all in-scope lifetimes; tail-expression temporaries drop earlier; async closures and AsyncFn* traits | explicit + '_; Fn(..) -> Fut with owned args |
Check rust-version in Cargo.toml (or rust-toolchain.toml) before suggesting GATs, use<..>, async fns in
traits or async closures.
Edition differences
| Topic | 2015 | 2018 / 2021 | 2024 |
|---|---|---|---|
| Borrow checker | lexical, then NLL from 1.36 | NLL | NLL |
'_ and impl-header elision | no | yes | yes |
Hidden lifetimes in paths (Formatter vs Formatter<'_>) | allowed | allowed; elided_lifetimes_in_paths (in the rust_2018_idioms group, allow-by-default) asks for <'_> | same |
-> impl Trait captures | type params only; lifetimes only if named in bounds (else E0700) | same | all in-scope type params and lifetimes; opt out with use<..> |
| Closure captures | whole variables | 2021: disjoint fields | disjoint fields |
| Tail-expression temporaries | dropped after locals | dropped after locals | dropped before locals (fixes some E0597 on x.borrow().len() at the end of a block) |
Migrating to 2024: cargo fix --edition runs impl_trait_overcaptures, which inserts use<..> where the new
default would capture more than before. Review those additions: many can go once you confirm callers do
not hold arguments while using the result.
Error codes that changed over time
Older answers on the web cite codes current rustc no longer emits; translate them:
| Old | Meaning | Today |
|---|---|---|
| E0495 cannot infer an appropriate lifetime | conflicting requirements | "lifetime may not live long enough" with '1/'2 labels |
| E0623 lifetime mismatch | data flows between two differently-named lifetimes | "lifetime may not live long enough" |
E0759 / E0772 'static requirement introduced by ... | a dyn Trait / impl Trait defaults to 'static | E0521 "borrowed data escapes", or "lifetime may not live long enough" with a note about 'static |
| E0700 hidden type captures lifetime | still emitted on editions <= 2021 | fixed by + '_ / use<'a> or edition 2024 |
Run rustc --explain E0106 for the full text of any current code.
Lints
| Lint | Tool | Catches |
|---|---|---|
clippy::needless_lifetimes | clippy (warn by default) | named lifetimes elision would produce (also elision_check LT001) |
clippy::extra_unused_lifetimes | clippy (warn by default) | declared and unused lifetimes (LT005) |
elided_lifetimes_in_paths | rustc (allow; enable via #![warn(rust_2018_idioms)]) | Formatter instead of Formatter<'_> |
unused_lifetimes | rustc (allow-by-default) | unused lifetime parameters |
single_use_lifetimes | rustc (allow-by-default) | a lifetime used once, replaceable by '_ (LT002) |
impl_trait_overcaptures | rustc (edition-2024 migration) | RPIT that would capture more in 2024 |
clippy::needless_pass_by_ref_mut, clippy::ref_option | clippy | API shapes that create needless borrows |
Enable in Cargo.toml for the whole workspace:
[lints.rust]
rust_2018_idioms = { level = "warn", priority = -1 }
unused_lifetimes = "warn"
[lints.clippy]
needless_lifetimes = "warn"
extra_unused_lifetimes = "warn"Testing lifetime guarantees
A lifetime in a public API is a promise: "the token does not borrow the parser", "the iterator owns its data". Lock such promises in with tests that fail to compile if someone changes the signature.
Positive tests (must compile): exercise the pattern callers rely on.
pub struct Parser<'a> { src: &'a str, pos: usize }
impl<'a> Parser<'a> {
pub fn new(src: &'a str) -> Self { Parser { src, pos: 0 } }
pub fn next_token(&mut self) -> Option<&'a str> {
let rest = self.src.get(self.pos..)?.trim_start();
if rest.is_empty() { return None; }
let start = self.src.len() - rest.len();
let end = rest.find(' ').unwrap_or(rest.len());
self.pos = start + end;
Some(&rest[..end])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokens_outlive_the_parser_borrow() {
let text = String::from("a b");
let mut p = Parser::new(&text);
let a = p.next_token();
let b = p.next_token(); // compiles only if next_token takes a short &mut self
drop(p); // tokens borrow `text`, not `p`
assert_eq!((a, b), (Some("a"), Some("b")));
}
fn is_static<T: 'static>(_: &T) {}
#[test]
fn config_is_owned() {
let cfg = String::from("x"); // stand-in for an owned config type
is_static(&cfg); // fails to compile if the type gains a borrowed field
}
}Negative tests (must not compile): compile_fail doctests or trybuild snapshots.
/// A token cannot outlive the source text:
///
/// ```compile_fail
/// let tok;
/// {
/// let text = String::from("a b");
/// let mut p = mycrate::Parser::new(&text);
/// tok = p.next_token();
/// }
/// println!("{tok:?}");
/// ```
pub fn _doc_anchor() {}compile_fail,E0597 additionally checks the error code (enforced on nightly). trybuild compares the full
compiler output against tests/ui/*.stderr; run TRYBUILD=overwrite cargo test after a compiler upgrade
changes the wording.
CI with the scripts
The scripts are single-file, std-only Rust programs: compile with rustc (about a second each), no Cargo
project needed, then run them as a gate next to cargo clippy.
SKILL=path/to/rust-lifetime-annotation-advisor
for t in elision_check missing_lifetime static_bounds lifetime_smells; do
rustc -O --edition 2021 "$SKILL/scripts/$t.rs" -o "/tmp/$t"
done
/tmp/missing_lifetime src/ --strict # high-severity: would not compile
/tmp/elision_check src/ --strict # noise: elidable and unused lifetimes
/tmp/static_bounds src/ --json > static.json # advisory: review, do not gate
/tmp/lifetime_smells src/ --max-lifetimes 2All scripts share options (--json, --strict, --select, --ignore, --edition, --list-rules) and
exit codes (0 clean or advisory, 1 findings with --strict, 2 usage error).
rust-borrow-checker-error-explainer
Explain and fix Rust borrow-checker, ownership, move and lifetime compiler errors: E0382 use of moved value, E0499 cannot borrow as mutable more than once, E0502 also borrowed as immutable, E0505, E0506, E0503, E0507 cannot move out of index/Rc/reference, E0515 return reference to local, E0597 does not live long enough, E0716 temporary value dropped while borrowed, E0373 closure may outlive (spawn needs move), E0521 borrowed data escapes, E0384, E0596, E0594, E0381, E0713, 'lifetime may not live long enough', RefCell 'already borrowed: BorrowMutError' panics. Ranks fixes from restructuring (split borrows, entry API, split_at_mut, get_disjoint_mut, mem::take, Option::take, indices, thread::scope) down to clone and Rc<RefCell>/Arc<Mutex>; never unsafe. Covers NLL limits (get-or-insert), iterator invalidation, closure captures, self-referential structs. Ships std-only Rust triage tools.
rust-cargo-workspace-designer
Design, review and fix Cargo workspaces: when to split a crate (compile time, boundaries, publishing, proc-macros), crates/* vs apps/ + crates/ layouts, virtual manifest vs root package, members/exclude/default-members, resolver 2 vs 3 (MSRV-aware, edition 2024), [workspace.package] and [workspace.dependencies] inheritance, [workspace.lints], root-only profiles (lto, codegen-units), additive features with dep: and weak ?/ syntax, feature unification pitfalls, internal path + version deps, publish = false, Cargo.lock and MSRV policy, xtask, CI with --locked, nextest, rust-cache, sccache, cargo-hack/deny/machete/udeps/semver-checks, and cargo build --timings. Ships a workspace auditor and crate-graph tool.
rust-error-handling-thiserror-anyhow-designer
Design and review Rust error handling with thiserror 2 and anyhow 1: library vs application split, typed error enums with #[from], #[source], #[error(transparent)] and #[non_exhaustive], ErrorKind patterns, context via .context()/.with_context(), bail!/ensure!, source() chains, {:#} and {:?} reports, RUST_BACKTRACE/RUST_LIB_BACKTRACE, Box<dyn Error + Send + Sync>, main -> anyhow::Result or ExitCode, unwrap/expect/panic policy, Option to Result, collecting iterators of Results, axum IntoResponse mapping, retryable errors, tracing, async Send bounds, testing with matches! and downcast_ref, no_std core::error::Error, and snafu, eyre/color-eyre, miette, error-stack.
rust-tokio-async-service-builder
Build and review production async Rust services on Tokio 1.x and axum 0.8: runtime choice (#[tokio::main] multi_thread vs current_thread, Builder), axum routing with /{id} paths, State, extractors, IntoResponse error types, axum::serve with_graceful_shutdown, tower/tower-http middleware (TraceLayer, TimeoutLayer, CorsLayer, ConcurrencyLimitLayer, RequestBodyLimitLayer), Arc<AppState>, std vs tokio Mutex, JoinSet, TaskTracker, CancellationToken, select! cancel safety, bounded mpsc, oneshot, broadcast, watch, actors, Semaphore, timeouts, retries, spawn_blocking, sqlx PgPool, reqwest Client reuse, tracing, tests with start_paused and oneshot, Dockerfile. Fixes 'future cannot be sent between threads safely', E0373, Rc or MutexGuard held across await, 'Cannot start a runtime from within a runtime', 'Path segments must not start with :'. Ships std-only Rust scanners and a compiling axum 0.8 scaffold.
rust-trait-design-reviewer
Review and design Rust traits and generic APIs: generics vs impl Trait vs dyn Trait (static vs dynamic dispatch), dyn compatibility / object safety (generic methods, Self returns, where Self: Sized, error[E0038] not dyn compatible / cannot be made into an object), associated types vs generic parameters, blanket impls, coherence and orphan rule (E0117, E0119, E0210), newtype, extension, sealed and marker traits, supertraits and trait upcasting (1.86), async fn in traits (1.75) and the Send bound problem (trait_variant, async-trait), RPITIT, GATs, From/Into/TryFrom/AsRef/Borrow, std trait checklist (Debug, Clone, PartialEq, Hash, Default, Display, Error, Send/Sync, serde feature), #[must_use], #[non_exhaustive], semver hazards, Deref abuse, builders, typestate, PhantomData, Box<dyn Error + Send + Sync>, Fn traits, mockall.
rust-unsafe-block-auditor
Audit unsafe Rust for soundness: inventory every unsafe block, unsafe fn, unsafe impl/trait, extern block and unsafe attribute, check // SAFETY: comments and # Safety docs, and classify each as sound, needs-justification or likely UB, proposing safe alternatives first. Covers the five unsafe superpowers, aliasing (Stacked/Tree Borrows), invalid values, MaybeUninit vs mem::zeroed/uninitialized, transmute, slice::from_raw_parts, Vec::set_len/from_raw_parts, get_unchecked, CString::as_ptr dangling, unsafe impl Send/Sync, Pin projection, FFI (extern "C", repr(C), C-unwind, Box::into_raw/from_raw), strict provenance, static mut and &raw, edition 2024 (unsafe extern, #[unsafe(no_mangle)], unsafe_op_in_unsafe_fn, env::set_var), Miri, sanitizers, cargo-fuzz, loom, cargo-geiger and clippy safety lints.