In rust, if I have the following code
const foo: AtomicBool = AtomicBool::new(false);
*foo.get_mut() = true;
println!("{}", foo.load(Ordering::SeqCst));
it prints false. There are no warnings (except to do with capitalization), and there is no errors, at compile time or runtime, but the value is not changed, which is not expected behavior. If the variable is declared using let
or static
, the compiler throws the following errors:
error[E0596]: cannot borrow `foo` as mutable, as it is not declared as mutable
--> src\bin\main.rs:6:6
|
4 | let foo: AtomicBool = AtomicBool::new(false);
| --- help: consider changing this to be mutable: `mut foo`
5 | //const bar: AtomicBool = foo;
6 | *foo.get_mut() = true;
| ^^^ cannot borrow as mutable
for let
, and
error[E0596]: cannot borrow immutable static item `foo` as mutable
--> src\bin\main.rs:6:6
|
6 | *foo.get_mut() = true;
| ^^^ cannot borrow as mutable
for static
.
Throwing an error like this is what I would expect, as I am trying to get a mutable borrow of an immutable value, so I have two questions:
- Why is no such error thrown for
const
, and - What is the correct way to use a global variable like this, as
const
does not seem to produce the inteded behavior
Related github issue: https://github.com/rust-lang/rust/issues/40543