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?
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).
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