Const fns - unstable function when using AtomicUsize :: new

What is wrong with this code?

use std::sync::atomic::AtomicUsize; static mut counter: AtomicUsize = AtomicUsize::new(0); fn main() {} 

I get this error:

 error: const fns are an unstable feature --> src/main.rs:3:35 |> 3 |> static mut counter: AtomicUsize = AtomicUsize::new(0); |> ^^^^^^^^^^^^^^^^^^^ help: in Nightly builds, add `#![feature(const_fn)]` to the crate attributes to enable 

The docs mention that other atomic sizes are unstable, but AtomicUsize seems to be stable.

The goal of this is to get an atomic counter for each process.

+5
source share
1 answer

Yes, you cannot call functions outside of a function starting with Rust 1.10. This requires an unstable function: a constant evaluation of the function.

You can initialize an atomic variable to zero using ATOMIC_USIZE_INIT (or the corresponding option):

 use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT}; static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT; fn main() {} 

As bluss points out , there is no need to make this mutable. And, as the compiler points out, the static and const values ​​must be in SCREAMING_SNAKE_CASE .

+9
source

All Articles