Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a Box within a const item?

Tags:

rust

I've tried things like this:

const b: Box<i32> = Box::new(5);

Which gave me that function calls in constants are limited to struct and enum constructors.

I also tried

const b: Box<i32> = box 5;

Which gave me an error saying that I should use Box::new instead. Is there any way to do this? I need a box because it's in a struct and the struct requires a box.

Edit: I know that Box::new is a function, and I can't use that in a const item. But is there another way to create a box that is allowed?

like image 693
Alex Knauth Avatar asked Jan 07 '16 19:01

Alex Knauth


1 Answers

Not right now, not in the immediate future.

As @Paolo mentioned, the only way to initialize a const variable is to use a constant expression. Today, in stable, it is limited to a restricted set of operations (some integers manipulation, some casts, ...).

There is a RFC to extend the set of expressions available in constant expressions: const fn. It is about allowing functions (both free functions and methods) to be marked const, making them available in constant expressions.

The tracking issue is #24111, and const fn can be used on nightly with the #![feature(const_fn)] crate attribute...

... however, at the moment, const fn are mostly about integral manipulations too. There is no plan that I know of to extend to arbitrary (side-effect-less) expressions, and thus it would not work for Box::new.


At the moment, you are advised to use lazy_static!, it will not allow the item to be const (it will be initialized on first use).

like image 163
Matthieu M. Avatar answered Nov 15 '22 07:11

Matthieu M.