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

标签 compiler-errors rust atomic

这段代码有什么问题?

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 ,没有必要使它可变。正如编译器指出的那样,staticconst 值应该在 SCREAMING_SNAKE_CASE 中。

关于compiler-errors - 使用 AtomicUsize::new 时,const fns 是一个不稳定的特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39452284/

相关文章:

compiler-errors - 未报告 Fortran 77 中参数错误中的排名不匹配

compilation - genbarcode 0.4-make : *** [.dep] Error 123

maven - 添加FaceletContext jsf maven时无法解决javax.el.E​​LContext错误

multithreading - 原子操作有多昂贵?

python - python中主线程和子线程之间的原子操作

compiler-errors - “unclassifiable statement” at if语句

function - Rust 中的函数原型(prototype)是什么?

rust - 特征 `Encodable` 是私有(private)的

rust - 从方法调用中使用rust 多个可变的 self 借用

c++ - std::shared_ptr 中的计数器是原子的吗?