Because mutable references are not Copy I get a compiler error when trying to use the array initialization syntax to create a new instance of an array of mutable values. How do I initialize this array with all Nones?
Compiling playground v0.0.1 (/playground)
error[E0277]: the trait bound `std::option::Option<&mut str>: std::marker::Copy` is not satisfied
--> src/main.rs:4:41
|
4 | let array: [Option<&mut str>; 16] = [None; 16];
| ^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::option::Option<&mut str>`
|
= help: the following implementations were found:
<std::option::Option<T> as std::marker::Copy>
= note: the `Copy` trait is required because the repeated element will be copied
= note: this array initializer can be evaluated at compile-time, see issue #49147 <https://github.com/rust-lang/rust/issues/49147> for more information
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
Ah, bummer. I'm not sure if there's a way to use a macro or not. Feels like there is, but looping over numbers is not the same as looping over syntax in macros, so I might still have to type 64 arbitrary different items, probably just a letter, into the macro just to give it something to loop over.
Still, I might not need 64 elements, so Default::default() might work for now.
Ah, OK, I figured that would probably be easy with unsafe, I was just looking at zeroed(), but it scared me when it wasn't valid for &mut or & types, but that didn't consider the Option in my case.
So for now I'll just use less than 64 elements, as I think 32 or maybe even less would probably be fine in my case ( It's like a "how many elements will users end up needing in practice?" question ), then I'll use the Default initialization.
I'd prefer to manually specify all the Nones than using a single line of unsafe {}. Unless it spans thousands of lines(not elements), I can say it has less maintenance cost than the single line of unsafe {}.
Really, it's just a matter of copy-pasting. Fill your first line with reasonable amount of Nones, maybe 8 or 16, and copy-paste it until the compiler stop throw the error. You can't make a mistake, the compiler check the number of elements.