As of Rust 1.79 (to be released in June 2024), a simple way to do this is using inline const:
struct Thing;
fn main() {
const SIZE: usize = 100;
let _array: [Option<Box<Thing>>; SIZE] = [const {None}; SIZE];
}
Playground
That also works for initializing static
variables.
As of Rust 1.63 (released in August 2022), a cleaner alternative to previously posted answers is possible using std::array::from_fn()
:
const SIZE: usize = 100;
let array: [Option<Box<Thing>>; SIZE] = std::array::from_fn(|_| None);
Playground
If you need to support Rust versions older than 1.63, or if you need to initialize a static
, an alternative approach using an intermediate const
initializer works as of Rust 1.38 (released in September 2019):
const SIZE: usize = 100;
const INIT: Option<Box<Thing>> = None; // helper
// also works with static array
let array: [Option<Box<Thing>>; SIZE] = [INIT; SIZE];
Playground
The first and the last approach have the limitation that the array item must have a representation that can be evaluated at compile time - a constant, enum variant, empty Vec or String, or a primitive container (enum, tuple) composed of those. None
or a tuple of numbers will work, but a non-empty Vec
or String
won't. The array::from_fn()
approach has no such limitation.
All the above examples work with or without the Box
; they use Box
because that was used in the question. All work for arrays of any size.
[Option<Box<T>>; N]
you can use transmute from a[0; N]
: is.gd/CC31YQ – Hydrodynamics