You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Taking a reference to a [`static mut`]is no longer allowed:
15
+
The [`static_mut_refs`] lint detects taking a reference to a [`static mut`]. In the 2024 Edition, this lint is now `deny` by default to emphasize that you should avoid making these references.
16
16
17
-
<!-- edition2024,E0796-->
17
+
<!-- edition2024 -->
18
18
```rust
19
19
staticmutX:i32=23;
20
20
staticmutY:i32=24;
21
21
22
22
unsafe {
23
-
lety=&X; // ERROR: reference of mutable static
24
-
letrefx=X; // ERROR: reference of mutable static
25
-
let (x, y) = (&X, &Y); // ERROR: reference of mutable static
23
+
lety=&X; // ERROR: shared reference to mutable static
24
+
letrefx=X; // ERROR: shared reference to mutable static
25
+
let (x, y) = (&X, &Y); // ERROR: shared reference to mutable static
26
26
}
27
27
```
28
28
29
29
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.
30
30
31
+
Note that there are some cases where implicit references are automatically created without a visible `&` operator. For example, these situations will also trigger the lint:
32
+
33
+
<!-- edition2024 -->
34
+
```rust
35
+
staticmutNUMS:&[u8; 3] =&[0, 1, 2];
36
+
37
+
unsafe {
38
+
println!("{NUMS:?}"); // ERROR: shared reference to mutable static
39
+
letn=NUMS.len(); // ERROR: shared reference to mutable static
40
+
}
41
+
```
42
+
31
43
## Alternatives
32
44
33
45
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).
@@ -40,6 +52,4 @@ In situations where no locally-reasoned abstraction is possible and you are ther
40
52
41
53
## Migration
42
54
43
-
🚧 The automatic migration for this has not yet been implemented.
44
-
45
-
<!-- TODO: Discuss alternatives around rewriting your code. -->
55
+
There is no automatic migration to fix these references to `static mut`. To avoid undefined behavior you must rewrite your code to use a different approach as recommended in the [Alternatives](#alternatives) section.
0 commit comments