In Rust 2024, why does `println!("{}", COUNTER)` on a `static mut COUNTER: u32` fail to compile while `COUNTER += 1` in the same unsafe block compiles?
answer
- a hidden borrow in a macro
- places versus references
- a lint that became deny
- raw borrow or an atomic
basics
~20 sprintln! borrows its arguments, so it creates a shared reference to the static mut, which the static_mut_refs lint denies by default on edition 2024. COUNTER += 1 writes the place directly and creates no reference.
solid answer
~40 sEvery access to a `static mut` needs `unsafe`, but inside the block Rust 2024 separates place operations from references. `COUNTER += 1` and `let n = COUNTER;` touch the static directly. `println!` takes a hidden `&COUNTER`, and the `static_mut_refs` lint, deny by default since the 2024 edition (a warning before), rejects it: `error: creating a shared reference to mutable static`. A reference is the hazard because it promises no mutation while it lives, a promise you cannot check for a global; a reference that breaks the aliasing rule is undefined behaviour even if never used. Fixes: copy the value out first, read through `&raw const COUNTER`, or better, replace the `static mut` with a `static AtomicU32`, a `Mutex` or a `LazyLock`, which need no `unsafe`.
code
rust · 10 linesstatic mut PUSHES: u32 = 0;
fn main() {
unsafe {
PUSHES += 1; // compiles: a place write, no reference
let n = PUSHES; // compiles: copies the value out
println!("{n}");
println!("{}", PUSHES); // error: shared reference to mutable static
}
}go deeper
Remember that every read or write of a static mut needs unsafe, and that std's atomics or Mutex in a plain static are the usual replacement.
Explain why a reference to a static mut is riskier than a single read or write, and spot the hidden reference in println! or a method call.
Diagnose the 2024 static_mut_refs error, choose between copying the value, a raw borrow and an atomic, and justify any remaining static mut in a SAFETY comment.
Make plain statics with interior mutability the default for global state, and treat each surviving static mut or allow(static_mut_refs) as a reviewed exception.
## Two kinds of access to a `static mut` A `static mut` is a global with one fixed address that any code may read or write. Every read or write of it is unsafe in Rust, because the compiler cannot see who else is touching it: reading or writing one outside `unsafe` fails with E0133, `use of mutable static is unsafe and requires unsafe block`. Inside the block, Rust distinguishes two kinds of access: - **Place operations** read or write the static directly: `PUSHES += 1`, `PUSHES = 0`, `let n = PUSHES;` for a `Copy` type. No reference is created, and an `unsafe` block is all they need. - **Taking a reference**: `&PUSHES`, `&mut PUSHES`, `let ref r = PUSHES`, or a method call that auto-borrows, such as `PUSHES.to_string()`. Each produces a `&u32` or `&mut u32` that lives for some span of code. The second kind is what the `static_mut_refs` lint flags. ## What the 2024 edition changed `static_mut_refs` detects shared or mutable references to a `static mut`. On editions up to 2021 it warns; on **edition 2024 it is deny by default**, so the code becomes a compile error. rustc 1.99.1 reports `error: creating a shared reference to mutable static` with the label `shared reference to mutable static`; there is no E-number, because it is a lint, part of `rust-2024-compatibility`. `println!` is the classic trap. The formatting macros take a reference to every argument behind the scenes, so `println!("{}", PUSHES)` creates `&PUSHES` even though no `&` appears in the source. The edition guide lists this case, and `NUMS.len()` on a `static mut` slice, as references the lint catches. `let n = PUSHES; println!("{n}")` compiles, because the macro then borrows the local copy. ## Why a reference is the dangerous part A reference carries promises a raw pointer does not: - a `&T` promises that nobody mutates the value while the reference lives; - a `&mut T` promises that nobody else reads or writes it while the reference lives; - a raw pointer promises nothing, so the obligations apply only at the moment it is dereferenced. rustc's note puts it plainly: it is undefined behaviour "if the static is mutated or if a mutable reference is created for it while the shared reference lives". The edition guide adds that taking such a reference in violation of the aliasing rule has always been undefined behaviour **even if it is never used**, and that checking the rule for a global needs reasoning about the whole program, including re-entrant calls and other threads. A place operation lasts one expression. A reference can live across function calls, which is where another write to the static can sneak in. ## The fixes, from best to last resort 1. **Avoid the mutable global.** Pass state explicitly. 2. **Use a type with interior mutability in a plain `static`:** - `static POPS: AtomicU32 = AtomicU32::new(0);` with `fetch_add`, for counters and flags; - `static QUEUE: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());` for larger state; - `LazyLock` or `OnceLock` for values initialised once at first use. None of these needs `unsafe`, and the type system checks access from other threads. 3. **Keep the `static mut`, but go through a raw pointer.** `&raw const PUSHES` and `&raw mut PUSHES` are safe to write since Rust 1.82; only the dereference needs `unsafe`, so the risky span shrinks to one expression with a `SAFETY` comment. 4. **Opt out** with `#[allow(static_mut_refs)]`. That silences the lint without making the reference any less dangerous, so a reviewer should ask for the reasoning. ## How the options compare | Approach | `unsafe` needed | Compiles on 2024 | Checked by the compiler | |---|---|---|---| | `println!("{}", PUSHES)` | yes | no, deny lint | nothing | | `let n = PUSHES;` then print `n` | yes | yes | nothing; you prove no data race | | `*(&raw const PUSHES)` | for the deref | yes | nothing; you prove no data race | | `static AtomicU32` | no | yes | thread-safe access | The second code example shows options 2 and 3 side by side. Why sharing a `static mut` with an interrupt handler or another thread breaks down in practice belongs to the material on interrupts and to the threads branch; the point here is the compiler's rule that a reference, not the access itself, is what the 2024 edition rejects.
- Does `#[allow(static_mut_refs)]` make the reference sound?No. It only silences the lint. The reference still promises that nothing mutates the static, or that nothing else accesses it for `&mut`, while it lives; if that fails, the program has undefined behaviour. A reviewer should treat the attribute as a claim that needs a `SAFETY` argument.
- Why is `let ref r = COUNTER;` caught by `static_mut_refs` while `let n = COUNTER;` is not?`let ref r` binds `r` by reference, so it creates `&COUNTER` exactly as `&COUNTER` would; the edition guide lists it among the errors. `let n = COUNTER;` copies the `u32` out, a place read that leaves no reference behind, so only the surrounding `unsafe` block is required.
- On edition 2024 every use of a static mut is a compile error.
- A reference to a static mut is harmless if it is never read.
- static_mut_refs is an E-coded hard error in every edition.
- An unsafe block around the println! makes the reference allowed.
- Replacing static mut with AtomicU32 still requires unsafe to update it.
Assumes Rust 1.99 on edition 2024, where static_mut_refs is deny by default; on edition 2021 the same code compiles with a warning, and &raw const is stable since Rust 1.82.