5

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • 3
    The atomic doesn't need to and should not be in a `static mut`, it should be in a plain `static`. Atomic operations use interior mutability when modifying them. You see that all their mutating methods use `&self` as the first argument (a shared reference). – bluss Sep 12 '16 at 18:34
  • 1
    Ah yes that makes sense, because they don't need to rely on the borrow checker. – Timmmm Sep 13 '16 at 08:28

1 Answers1

9

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.

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366