这段代码有什么问题?
use std::sync::atomic::AtomicUsize;
static mut counter: AtomicUsize = AtomicUsize::new(0);
fn main() {}
我收到这个错误:
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
文档提到其他原子 int 大小是不稳定的,但 AtomicUsize
显然是稳定的。
这样做的目的是获得一个原子的每进程计数器。
最佳答案
是的,从 Rust 1.10 开始,您不能在函数外部调用函数。这需要一个尚未稳定的特性:常量函数求值。
您可以使用 ATOMIC_USIZE_INIT
将原子变量初始化为零(或适当的变体):
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT};
static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
fn main() {}
作为bluss points out ,没有必要使它可变。正如编译器指出的那样,static
和 const
值应该在 SCREAMING_SNAKE_CASE
中。
关于compiler-errors - 使用 AtomicUsize::new 时,const fns 是一个不稳定的特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452284/