Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust 2024 edition: static mut references and if-let drop order

Edition 2024 denies shared references to static mut and drops if-let temporaries earlier. Both are silent until the build or a deadlock changes.

~5 min readRust
#Rust#Edition 2024#Borrow Checker#Migration
A mutable static block locked by a red deny sign and a shifted drop arrow, headline EDITION 2024

Introduction & Quick Summary

Symptom. cargo fix --edition finishes cleanly, you set edition = "2024", and the build immediately stops:

code
error: creating a shared reference to mutable static --> src/main.rs:61:22 | 61 | let c = unsafe { &COUNTER }; | ^^^^^^^^ shared reference to mutable static | = note: `#[deny(static_mut_refs)]` (part of `#[deny(rust_2024_compatibility)]`) on by default

Elsewhere a function that compiled for years now fails with E0597: borrowed value does not live long enough at the last expression of a block, or a Mutex-guarded if let stops deadlocking — behaviour that changed with no compiler error at all.

Cause. Edition 2024 changes three things that matter here. References to static mut are denied by default. Temporaries generated while evaluating an if let scrutinee are dropped before the else branch runs, which fixes a class of deadlock and breaks code that depended on the old lifetime. And the temporary in a block's tail expression is now dropped before the block's locals, which changes what E0597 accepts.

Fix. Replace the reference with a raw pointer or an atomic, and decide the drop order per if let instead of trusting a lint that under-reports.

rust
use std::sync::atomic::{AtomicUsize, Ordering}; static COUNTER: AtomicUsize = AtomicUsize::new(0); fn bump() -> usize { COUNTER.fetch_add(1, Ordering::Relaxed) }
rust
// if you really need the pointer, take it raw static mut BUFFER: [u8; 64] = [0; 64]; let p = &raw const BUFFER;

Core Mechanics, Signatures & Reproducible Setup

cargo fix --edition migrates a crate mechanically: gen becomes r#gen, extern blocks need unsafe, #[no_mangle] becomes #[unsafe(no_mangle)], and match ergonomics results are adjusted with explicit & patterns where the new rules resolve differently. What it cannot do is decide runtime semantics, so it prints warnings for lints like tail_expr_drop_order and leaves the decision to you.

Set up a crate to see each change in isolation:

bash
cargo new --lib ed2024 && cd ed2024 printf 'edition = "2021"\n' >> Cargo.toml cargo fix --edition --allow-dirty sed -i 's/edition = "2021"/edition = "2024"/' Cargo.toml cargo build

Now the static mut example fails with the error above. Two lints explain the silent changes; turn them on explicitly before you migrate, so you see them while the code still compiles:

rust
#![warn(if_let_rescope)] #![warn(tail_expr_drop_order)]

if_let_rescope proposes rewriting to match, which preserves the 2021 drop order. It only fires when a value with a significant Drop is created on the right-hand side, and it has a known gap: a guard used through a method call, as in cache.lock().unwrap().get(&k), is not reported. That is the line that changes behaviour without a warning.

Key Comparison Table

ConstructEdition 2021Edition 2024Migration
&STATIC_MUTallowed, warningstatic_mut_refs deny&raw const, atomic, or OnceLock
if let temporarieslive until the else endsdropped before elserewrite as match if order matters
Block tail temporaryextended outwarddropped at the block endbind to a local first
gen as an identifierallowedreserved keywordr#gen
extern "C" { fn f(); }no unsafe neededunsafe extern requiredunsafe extern "C" { ... }
#[no_mangle]bare attribute#[unsafe(no_mangle)]unsafe attribute
Resolver2 by default3set resolver per workspace
impl Trait capturenarrowcaptures all lifetimesadd explicit bounds if needed
SymptomCauseFix
static_mut_refs on &MUTshared reference to mutable staticraw pointer or atomic
E0597 at the last block expressiontail temporary dropped earlybind to a local, then use it
Deadlock disappearedif let guard released earlyuse match for the old order
Behaviour changed in else without a warningguard accessed via a method callinspect every guard-bearing if let
error: expected identifier, found keyword gennew reserved keywordr#gen
Dependency resolution changedresolver 3pin versions or set resolver = "2"

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. static mut is the one hard error

The compiler's suggestion, &raw const, changes the type to a raw pointer, which prints as an address and is not what most let c = &COUNTER; call sites wanted. For a read-only counter, copy the value; for a shared counter, use an atomic:

rust
// wrong suggestion applied blindly: prints an address let c = unsafe { &raw const COUNTER }; // what the code meant let c = unsafe { COUNTER };

For anything touched by more than one thread, AtomicUsize, Mutex or OnceLock removes the unsafe entirely and is the edition guide's own recommendation.

2. The if let guard that stopped deadlocking

A cache lookup written the 2021 way deadlocks with a Mutex, because the guard lives until the whole if let ends, and the else branch tries to lock again:

rust
// 2021: deadlocks with Mutex, panics with RefCell fn lookup(cache: &RefCell<HashMap<u32, String>>, k: u32) -> String { if let Some(v) = cache.borrow().get(&k) { v.clone() } else { let v = format!("value-{k}"); cache.borrow_mut().insert(k, v.clone()); v } }

In 2024 the scrutinee temporary is dropped before else, so the same code works. That is an improvement, and it is also a silent semantic change: if your else branch relied on the guard being held for exclusion, it no longer is. Rewrite as match to keep the old order deliberately:

rust
match cache.borrow().get(&k).cloned() { Some(v) => v, None => { let v = format!("value-{k}"); cache.borrow_mut().insert(k, v.clone()); v } }

3. Tail expression temporaries and E0597

A RefCell borrow returned from the last expression of a function used to fail; 2024 drops the temporary first, so it compiles. The inverse case is a String borrowed inside a block:

rust
// works in 2021, fails in 2024: the String temporary dies at the block end let x = { &String::from("1234") }.len(); // fix: lift the value out of the block let s = { &String::from("1234") }; let x = s.len();

Temporary lifetime extension still applies when the reference is bound to a name, which is why the second form works and the first does not.

4. Resolver 3 and dependency drift

edition = "2024" implies resolver = "3", which prefers dependency versions whose rust-version matches yours. A workspace that previously resolved to a newer crate may now pick an older compatible one, and a virtual workspace still has to set resolver on [workspace] because the edition belongs to the package, not the workspace:

toml
[workspace] resolver = "3" members = ["crates/*"]

If a build suddenly resolves different versions, compare cargo tree before and after rather than assuming the lockfile is wrong.

5. unsafe extern and attributes

Edition 2024 requires unsafe extern blocks and unsafe attributes. Bindgen output and FFI crates need regenerating, not hand-editing:

rust
unsafe extern "C" { fn legacy_init(flags: u32) -> i32; } #[unsafe(no_mangle)] pub extern "C" fn entry() -> i32 { 0 }

A crate that ships pre-generated bindings needs a version that targets 2024, or the build fails in a file you never wrote.

6. Match ergonomics edge cases

Patterns that used to bind by reference now bind by value in some &-matched positions, and the fix cargo fix applies is an explicit & pattern. Review those diffs instead of accepting them all: an added & can turn a move into a borrow, which is correct for the migration and wrong if the function later needs ownership.

rust
// 2021 match &Some(String::from("x")) { Some(s) => { let _: &String = s; } None => {} }

Run the whole workspace with cargo clippy --all-targets after the edition bump; clippy's lints are edition-aware and catch the guard cases the compiler lint skips. Two other releases in the same window, Rust 1.93 through 1.99, also tightened unsafe and closure capture rules, so read the release notes for the versions you skipped rather than only the edition guide.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Accepting every cargo fix rewrite. It is mechanical; the drop-order and borrow decisions are yours.
  • Applying &raw const where a value was read. The code compiles and prints an address instead of the counter.
  • Assuming no warning means no change. if_let_rescope misses guards accessed through method calls.
  • Bumping the edition in a virtual workspace root. edition is per package; the workspace needs resolver explicitly.
  • Forgetting rust-version in Cargo.toml. Resolver 3 uses it to choose dependencies, and without it you get the least predictable resolution.
  • Leaving generated FFI bindings alone. unsafe extern is a syntax requirement, not a style preference.
  • Upgrading the toolchain and the edition in one commit. Split them: the compiler version brings its own lints and you will not know which change caused which error.

Compare an old and new cargo tree with the text diff tool when the build starts resolving different crates, and format the Cargo.toml you are editing with the YAML and config formatter only after checking TOML validity.

Reference: The Rust 2024 Edition Guide and tail expression temporary scope.

Official references

primary documentation

The Rust documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.