Skip to content

Commit 5a04fd5

Browse files
authored
Merge pull request #299 from eggyal/disallow-static-mut-refs
Flesh out detail behind disallowing refs to static mut
2 parents eb3eb80 + 6606854 commit 5a04fd5

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

src/rust-2024/static-mut-reference.md

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,17 @@ unsafe {
2525
}
2626
```
2727

28-
Shared or mutable references of mutable static are almost always a mistake and can lead to undefined behavior and various other problems in your code.
29-
For example, another thread writing to the `static mut` will cause an aliasing violation and incur [Undefined Behavior].
28+
Merely taking such a reference in violation of Rust's mutability XOR aliasing requirement has always been *instantaneous* [undefined behavior], **even if the reference is never read from or written to**. Furthermore, upholding mutability XOR aliasing for a `static mut` requires *reasoning about your code globally*, which can be particularly difficult in the face of reentrancy and/or multithreading.
3029

31-
<!-- TODO: Discuss possible alternatives. -->
30+
## Alternatives
31+
32+
Wherever possible, it is **strongly recommended** to use instead an *immutable* `static` of a type that provides *interior mutability* behind some *locally-reasoned abstraction* (which greatly reduces the complexity of ensuring that Rust's mutability XOR aliasing requirement is upheld).
33+
34+
In situations where no locally-reasoned abstraction is possible and you are therefore compelled still to reason globally about accesses to your `static` variable, you must now use raw pointers such as can be obtained via the [`addr_of_mut!`] macro. By first obtaining a raw pointer rather than directly taking a reference, (the safety requirements of) accesses through that pointer will be more familiar to `unsafe` developers and can be deferred until/limited to smaller regions of code.
3235

3336
[Undefined Behavior]: ../../reference/behavior-considered-undefined.html
3437
[`static mut`]: ../../reference/items/static-items.html#mutable-statics
38+
[`addr_of_mut!`]: https://docs.rust-lang.org/core/ptr/macro.addr_of_mut.html
3539

3640
## Migration
3741

0 commit comments

Comments
 (0)