Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const fns are an unstable feature when using AtomicUsize::new

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.

like image 893
Timmmm Avatar asked Sep 12 '16 14:09

Timmmm


People also ask

Why can't I use const FN in a callable way?

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.

What are Fn traits in C++?

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.

Where can I find more information about an unstable feature?

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 in rust?

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.


1 Answers

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.

like image 163
Shepmaster Avatar answered Sep 29 '22 06:09

Shepmaster