Open
Description
Description
Since 1.83, the compiler warns when creating a shared reference to a mutable static:
static mut FOO: Option<String> = None;
let is_some = unsafe { &FOO }.is_some();
print!("{is_some:?}");
Gives this warning:
warning: creating a shared reference to mutable static is discouraged
--> src/main.rs:2:28
|
2 | let is_some = unsafe { &FOO }.is_some();
| ^^^^ shared reference to mutable static
|
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2024/static-mut-references.html>
= note: shared references to mutable statics are dangerous; it's undefined behavior if the static is mutated or if a mutable reference is created for it while the shared reference lives
= note: `#[warn(static_mut_refs)]` on by default
help: use `&raw const` instead to create a raw pointer
|
2 | let is_some = unsafe { &raw const FOO }.is_some();
Following the suggestion, we can write this:
static mut FOO: Option<String> = None;
let value = unsafe { &*&raw const FOO }.is_some();
print!("{value:?}");
But then clippy says this:
warning: immediately dereferencing a reference
--> src/main.rs:2:27
|
2 | let value = unsafe { &*&raw const FOO }.is_some();
| ^^^^^^^^^^^^^^^ help: try: `FOO`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#deref_addrof
= note: `#[warn(clippy::deref_addrof)]` on by default
I get why clippy says that, but I don't really see a clean solution to this with the current lints, apart from simply disabling one of them.
A different way to look at it: the suggested fix from clippy triggers the static_mut_refs
lint.
Version
rustc 1.83.0 (90b35a623 2024-11-26)
binary: rustc
commit-hash: 90b35a6239c3d8bdabc530a6a0816f7ff89a0aaf
commit-date: 2024-11-26
host: x86_64-unknown-linux-gnu
release: 1.83.0
LLVM version: 19.1.1
Additional Labels
@rustbot label D-confusing