1

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:

  1. Why is no such error thrown for const, and
  2. 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

Liam Bloom
  • 164
  • 2
  • 10
  • Similar question: https://stackoverflow.com/q/50631189/11326662 – Liam Bloom Nov 07 '20 at 05:04
  • Looks like a duplicate to me. `const`s aren't variables and they don't act like variables. If you disagree, please [edit] the question to explain how it's different. – trent Nov 07 '20 at 05:44
  • As for question 2., it seems you've already figured out that `static` is the way to create a "global" variable, so... why look any farther than what you've already seen works? – trent Nov 07 '20 at 05:46

0 Answers0