Timmmm
Timmmm

Reputation: 96832

const fns are an unstable feature 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 int sizes are unstable, but AtomicUsize is apparently stable.

The purpose of this is to get an atomic per-process counter.

Upvotes: 5

Views: 596

Answers (1)

Shepmaster
Shepmaster

Reputation: 431679

Yes, you cannot call functions outside of a function as of Rust 1.10. That requires a feature that is not yet stable: constant function evaluation.

You can initialize an atomic variable to zero using ATOMIC_USIZE_INIT (or the appropriate variant):

use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};

static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;

fn main() {}

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

Upvotes: 9

Related Questions