Alex Knauth
Alex Knauth

Reputation: 8373

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

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?

Upvotes: 7

Views: 2965

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299890

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

Upvotes: 6

Paolo Falabella
Paolo Falabella

Reputation: 25844

As the const and static chapter of the book says:

Both const and static have requirements for giving them a value. They may only be given a value that’s a constant expression. In other words, you cannot use the result of a function call or anything similarly complex or at runtime.

Box::new() is a function, so it falls in the scope of things you can't do to initialize a const. You can look at lazy-static for a way to initialize a static variable at runtime.

Upvotes: 0

Related Questions