I’m trying to initialize a fixed-size array of some nullable, non-copyable type, like an Option<Box<Thing>>
for some kind of Thing
. I’d like to pack two of them into a struct without any extra indirection. I’d like to write something like this:
let array: [Option<Box<Thing>>; SIZE] = [None; SIZE];
But it doesn’t work because the [e; n]
syntax requires that e
implements Copy
. Of course, I could expand it into SIZE
None
s, but that can be unwieldy when SIZE
is large. I don’t believe this can be done with a macro without an unnatural encoding of SIZE
. Is there a good way to do it?
Yes, this is easy with unsafe
; is there a way to do it without unsafe
?
You could use the Default
trait to initialize the array with default values:
let array: [Option<Box<Thing>>; SIZE] = Default::default();
See this playground for a working example.
Note that this will only work for arrays with up to 32 elements, because Default::default
is only implemented for up to [T; 32]
. See https://doc.rust-lang.org/std/default/trait.Default.html#impl-Default-98
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