使用AtomicUsize :: new时const fns是不稳定的功能 [英] const fns are an unstable feature when using AtomicUsize::new
问题描述
此代码有什么问题?
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
显然是稳定的.
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.
推荐答案
是的,从Rust 1.10开始,您不能在函数外部调用函数.这就需要一个尚未稳定的功能:常数函数评估.
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() {}
浮夸指出,不需要使它可变.正如编译器指出的那样,static
和const
值应位于SCREAMING_SNAKE_CASE
中.
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
.
这篇关于使用AtomicUsize :: new时const fns是不稳定的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!