Which Rust release changed what the borrow checker accepts, which APIs remove the need for workarounds, and how to lock fixes in with tests and CI.
Contents
- Stabilisations that matter for borrow errors
- Edition 2021 changes
- Edition 2024 changes
- Checking your MSRV before suggesting an API
- Testing that code does not compile
- Testing runtime borrow failures
- CI with the scripts
Stabilisations that matter for borrow errors
| Rust | Feature | Replaces |
|---|---|---|
| 1.31 | NLL on edition 2018 | lexical lifetimes (borrows lasting to the closing brace) |
| 1.36 | NLL on edition 2015 too | |
| 1.40 | mem::take | mem::replace(&mut x, Default::default()) |
| 1.53 | IntoIterator for arrays by value (edition 2021 for method syntax) | .iter().cloned() on arrays |
| 1.61 | Vec::retain_mut | index loops with remove |
| 1.63 | std::thread::scope; old AST borrow checker removed | crossbeam::scope, Arc for borrowed data |
| 1.65 | let ... else; generic associated types | nested match for E0381; workarounds for lending iterators |
| 1.70 | OnceCell/OnceLock; Arc::into_inner, Rc::into_inner | lazy_static, racy try_unwrap loops |
| 1.73 | panic message on its own line (panicked at src/x.rs:1:2:) | panicked at 'msg', src/x.rs:1:2 (both parsed by runtime_panic) |
| 1.76 | Rc::unwrap_or_clone, Arc::unwrap_or_clone | `try_unwrap(..).unwrap_or_else( |
| 1.77 | Mutex::clear_poison, RwLock::clear_poison | rebuilding the mutex after a panic |
| 1.80 | LazyCell/LazyLock; Option::take_if | once_cell::sync::Lazy; manual if pred { x.take() } |
| 1.82 | precise capturing impl Trait + use<'a, T>; &raw const/&raw mut | Captures<'a> trick |
| 1.85 | edition 2024; async closures (async || {}) | |
| 1.86 | <[T]>::get_disjoint_mut, HashMap::get_disjoint_mut; trait upcasting | split_at_mut gymnastics |
| 1.87 | Vec::extract_if, LinkedList::extract_if | retain + clone into a second Vec |
Edition 2021 changes
- Disjoint closure captures: closures capture the exact paths they use (
self.a.b), not whole variables. Fixes many E0502/E0499 errors with closures inside methods. Side effect: drop order of captured values can change;cargo fix --editioninsertslet _ = &x;where it matters. array.into_iter()yields values, not references (method syntax), which can move arrays you expected to borrow.- Panics:
panic!("{}")requires a format string; not borrow related.
Edition 2024 changes
Edition 2024 (Rust 1.85) changes several rules that affect borrows:
| Change | Effect on borrow errors |
|---|---|
| Tail-expression temporaries are dropped before the block's locals | Fixes classic E0597 "borrowed value does not live long enough" on fn f() -> usize { let c = RefCell::new(..); c.borrow().len() } |
if let scrutinee temporaries are dropped before the else block | if let Some(x) = m.lock().unwrap().get(..) {} else { m.lock() } no longer deadlocks; may change drop order |
RPIT (-> impl Trait) captures all in-scope generic parameters, including lifetimes | Can introduce E0502/E0505 at call sites: the returned value now borrows arguments it did not before. Fix with + use<..> listing only what is captured |
static mut references are denied (static_mut_refs) | use atomics, Mutex, OnceLock, or &raw mut |
unsafe_op_in_unsafe_fn warns | unrelated to borrows, appears in the same migration |
Migrate with cargo fix --edition on 2021, check, then set edition = "2024" and re-run cargo check;
run parse_diagnostics on the output to triage new borrow errors.
// Edition 2024 RPIT capture and its precise-capturing fix (1.82+ syntax, works on 2021 too).
fn evens<'a>(v: &'a [u32], _scratch: &mut Vec<u32>) -> impl Iterator<Item = u32> + use<'a> {
v.iter().copied().filter(|x| x % 2 == 0) // captures 'a only, not the `_scratch` borrow
}Checking your MSRV before suggesting an API
- Read
rust-versioninCargo.toml(or the toolchain inrust-toolchain.toml). - Below 1.86: suggest
split_at_mut, notget_disjoint_mut. Below 1.87:retain(+ clone) instead ofextract_if. Below 1.80:once_cellcrate instead ofLazyLock. Below 1.65: nolet ... else. - The
explain_codefix lists name the minimum version next to each newer API. cargo +1.70 check(with that toolchain installed) orcargo msrv verifyconfirm a fix builds on the MSRV.
Testing that code does not compile
Keep a regression test for "this misuse must stay a compile error", for example a type that must not be
Send, or an API whose returned reference must not outlive its owner.
compile_fail doctests (stable, no extra crates):
/// The guard cannot outlive the pool:
///
/// ```compile_fail,E0597
/// let conn;
/// {
/// let pool = mycrate::Pool::new();
/// conn = pool.get();
/// }
/// conn.query("select 1");
/// ```
pub struct Pool;The error code after compile_fail, makes rustdoc check that the failure is the expected one (the code check
is enforced on nightly; stable only checks that it fails). Prefer tests that fail for exactly one reason.
trybuild (dev-dependency) compares full compiler output with .stderr snapshots:
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/*.rs"); // each file must fail; output compared to tests/ui/*.stderr
t.pass("tests/ui-pass/*.rs");
}Run TRYBUILD=overwrite cargo test to accept new snapshots after a compiler upgrade changes wording.
Testing runtime borrow failures
use std::cell::RefCell;
struct Bus { listeners: RefCell<Vec<String>> }
impl Bus {
fn emit(&self) -> usize {
let snapshot = self.listeners.borrow().clone(); // guard dropped before calling out
for _l in &snapshot {
self.listeners.borrow_mut().push("re-subscribed".into());
}
snapshot.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn emit_can_resubscribe() {
let bus = Bus { listeners: RefCell::new(vec!["a".into()]) };
assert_eq!(bus.emit(), 1);
assert_eq!(bus.listeners.borrow().len(), 2);
}
#[test]
#[should_panic(expected = "already borrowed")]
fn holding_a_guard_while_mutating_panics() {
let cell = RefCell::new(vec![1]);
let _r = cell.borrow();
cell.borrow_mut().push(2);
}
}For mutexes, test the recovery path: spawn a thread that panics while holding the lock, join() it (it
returns Err), then assert that lock() returns Err and that your recovery (into_inner/clear_poison)
works.
CI with the scripts
The scripts are single-file, std-only Rust programs: build with rustc, no Cargo project needed.
SKILL=path/to/rust-borrow-checker-error-explainer
for t in parse_diagnostics runtime_panic; do
rustc -O --edition 2021 "$SKILL/scripts/$t.rs" -o "/tmp/$t"
done
# Fail fast with an explanation when a PR introduces borrow errors:
cargo check --all-targets --message-format=json > check.jsonl || /tmp/parse_diagnostics check.jsonl
# Explain RefCell / Mutex panics in test failures:
cargo test 2>&1 | tee test.txt || /tmp/runtime_panic test.txt--strict makes either tool exit 1 when the output contains errors or panics that are not borrow-related, so
a pipeline step can tell "borrow problem, see explanation" from "something else broke".
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-lifetime-annotation-advisor
Decide when Rust lifetime annotations are needed and which ones: the three elision rules, structs holding references (struct Parser<'a>), owned vs borrowed (String, &str, Cow<'a, str>, Arc<str>), one vs several lifetimes, 'a: 'b bounds, T: 'static misconceptions, Box<dyn Trait + 'a> default object lifetimes, impl Trait + '_ and edition 2024 capture rules with use<..>, variance and PhantomData, HRTB for<'a> Fn(&'a T), GATs and lending iterators, async fn and tokio::spawn 'static, self-referential structs (ouroboros, self_cell, indices, arenas), Rc/Arc to escape lifetime soup. Ships std-only Rust checkers for redundant, missing, unused and over-restrictive lifetimes.
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.