Why do `sync::atomic` types require method to initialize?


#1

I find myself annoyed and puzzled that I cannot create an AtomicBool as a static variable. Yes, I could use lazy_static and wrap it in a deref method, but it really seems like the AtomicBool should be able to be initialized in precisely the same way that an ordinary static bool is initialized. Why is this not possible?


#2

https://doc.rust-lang.org/std/sync/atomic/constant.ATOMIC_BOOL_INIT.html


#3

I believe it’s because internally it uses an UnsafeCell, but this cell isn’t pub. If you use nightly you can do something like this to create a static AtomicBool, but const functions aren’t stable yet.

#![feature(const_fn)]
use std::sync::atomic::AtomicBool;
static mut SOME_FLAG: AtomicBool = AtomicBool::new(false);

fn main() {
    println!("{:?}", SOME_FLAG);
}

Otherwise on stable you need to use the ATOMIC_BOOL_INIT which just uses const_fn internally (because std is special and allowed to use unstable stuff on stable).

use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT};
static SOME_FLAG: AtomicBool = ATOMIC_BOOL_INIT;

fn main() {
    println!("{:?}", SOME_FLAG);
}