使用AtomicUsize :: new时,const fns是一个不稳定的特性

Tim*_*mmm 5 compiler-errors atomic rust

这段代码有什么问题?

use std::sync::atomic::AtomicUsize;

static mut counter: AtomicUsize = AtomicUsize::new(0);

fn main() {}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

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
Run Code Online (Sandbox Code Playgroud)

文档提到其他原子int大小不稳定,但AtomicUsize显然是稳定的.

这样做的目的是获得一个原子每进程计数器.

She*_*ter 9

是的,你不能在Rust 1.10之外调用函数之外的函数.这需要一个尚不稳定的功能:恒定功能评估.

您可以使用ATOMIC_USIZE_INIT(或适当的变体)将原子变量初始化为零:

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

static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;

fn main() {}
Run Code Online (Sandbox Code Playgroud)

作为bluss指出,没有必要做出这种改变的.而作为编译器指出,staticconst值应在SCREAMING_SNAKE_CASE.