Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a large, fixed-size array with non-Copy types

Tags:

rust

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 Nones, 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?

like image 787
rieux Avatar asked Feb 22 '15 09:02

rieux


1 Answers

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

like image 68
rnstlr Avatar answered Oct 01 '22 08:10

rnstlr