@@ -22,6 +22,7 @@ static mut COUNTER: u32 = 0;
22
22
23
23
fn add_to_counter(inc: u32) {
24
24
// SAFETY: There are no other threads which could be accessing `COUNTER`.
25
+ #[allow(static_mut_refs)]
25
26
unsafe {
26
27
COUNTER += inc;
27
28
}
@@ -31,6 +32,7 @@ fn main() {
31
32
add_to_counter(42);
32
33
33
34
// SAFETY: There are no other threads which could be accessing `COUNTER`.
35
+ #[allow(static_mut_refs)]
34
36
unsafe {
35
37
println!("COUNTER: {COUNTER}");
36
38
}
@@ -40,12 +42,16 @@ fn main() {
40
42
<details >
41
43
42
44
- The program here is safe because it is single-threaded. However, the Rust
43
- compiler is conservative and will assume the worst. Try removing the ` unsafe `
44
- and see how the compiler explains that it is undefined behavior to mutate a
45
- static from multiple threads.
46
-
47
- - Using a mutable static is generally a bad idea, but there are some cases where
48
- it might make sense in low-level ` no_std ` code, such as implementing a heap
49
- allocator or working with some C APIs.
45
+ compiler reasons about functions individually so can't assume that. Try
46
+ removing the ` unsafe ` and see how the compiler explains that it is undefined
47
+ behavior to access a mutable static from multiple threads.
48
+ - Rust 2024 edition goes further and makes accessing a mutable static by
49
+ reference an error by default. We work around this in the example with
50
+ ` #[allow(static_mut_refs)] ` . Don't do this.
51
+ - Using a mutable static is almost always a bad idea, you should use interior
52
+ mutability instead.
53
+ - There are some cases where it might be necessary in low-level ` no_std ` code,
54
+ such as implementing a heap allocator or working with some C APIs. In this
55
+ case you should use pointers rather than references.
50
56
51
57
</details >
0 commit comments