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
?
I'm copying the answer by chris-morgan and adapting it to match the question better, to follow the recommendation by dbaupp downthread, and to match recent syntax changes:
Note the need to use
unsafe
here: The problem is that if the constructor functionpanic!
s, this would lead to undefined behavior.You could use the
Default
trait to initialize the array with default values:See this playground for a working example.