Why not panic when try to change a const value likes Atomic?

Hey, I am creating a global value created by AtomicBool,

the correct way is
pub static val: AtomicBool = AtomicBool::new(true);

but i write it on a wrong way
pub const val: AtomicBool = AtomicBool::new(true);

rustc do not panic when I change val by val.store(false, Ordering::SeqCst);
and val didn't change as i wish ,

I just feel a little confused about it

There is a compiler warning for this, but I think it might be a clippy warning.

in fact, maybe take a warning when build will be better?

change a const value is a dangerous and unreasonable behavior

cargo build / cargo run should provide a warning for this, not in cargo clippy.

code in here

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;

pub const A: AtomicBool = AtomicBool::new(true);


fn main() {
    A.store(false, SeqCst);
    println!("Hello, world!");
}

output

C:\Users\Administrator\CLionProjects\xx>cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.00s
     Running `target\debug\xx.exe`
Hello, world!

C:\Users\Administrator\CLionProjects\xx>cargo clippy
warning: a `const` item should never be interior mutable
 --> src\main.rs:4:1
  |
4 | pub const A: AtomicBool = AtomicBool::new(true);
  | -----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  | |
  | make this a static item (maybe with lazy_static)
  |
  = note: `#[warn(clippy::declare_interior_mutable_const)]` on by default
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const

warning: a `const` item with interior mutability should not be borrowed
 --> src\main.rs:8:5
  |
8 |     A.store(false, SeqCst);
  |     ^
  |
  = note: `#[warn(clippy::borrow_interior_mutable_const)]` on by default
  = help: assign this const to a local or static variable, and use the variable here
  = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#borrow_interior_mutable_const

warning: 2 warnings emitted

    Finished dev [unoptimized + debuginfo] target(s) in 0.02s

The relevant issue is here: Uplift `declare_interior_mutable_const` and `borrow_interior_mutable_const` from clippy to rustc · Issue #77983 · rust-lang/rust · GitHub

You can post a comment on it.

i see, thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.