Const meet interior mutability

#![allow(unused)]
use std::sync::atomic::{AtomicBool,Ordering};

const FLAG: AtomicBool = AtomicBool::new(true);

fn main() {
    println!("{}", FLAG.load(Ordering::Relaxed));
    FLAG.store(false, Ordering::Relaxed);
    println!("{}", FLAG.load(Ordering::Relaxed));
    FLAG.store(false, Ordering::Relaxed);
    println!("{}", FLAG.load(Ordering::Relaxed));

}

This code doesn't work as expected, but no error or warning appears.
How this works?

Constants in Rust are like #defines in C - they are inlined into every place they're used. To have one global value operated from multiple places, use static.

6 Likes

const means that the value just gets copied around, so you're actually just mutating a temporary. If you want all mentions of FLAG to refer to the same value, then you should do as @Cerber-Ursi says, and use static

Using const is the same as,

const FLAG: bool = true;

fn main() {
    println!("{}", FLAG);
    *(&mut FLAG) = true; //mutate temp
    println!("{}", FLAG);
    *(&mut FLAG) = false; //mutate temp
    println!("{}", FLAG);
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.