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.
We are overaggressive in keeping the door open for future features in const fn. The error you are encountering was created in order to prevent users from writing functions like since it is impossible to use f in a callable way. The following function is illegal right now.
The three traits Fn, FnMut and FnOnce are known as the fn traits. They are automatically implemented for any functions or closures that you create and are what provides the ability to pass arguments to them.
If you wish to read more about an unstable feature the best place to start is the unstable book where most of them are listed. The unstable book then links to a tracking issue which then often, in turn, links to an RFC . With this combination of sources, you can then build up a picture of the details surrounding a feature.
Why use unstable features Unstable Rust can enable you to write API's that you could not express in stable Rust. Unstable features are used within both the compiler and standard library for that very reason. Using unstable features always comes with some risk.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With