I have a struct, which contains the following 2D array:
board: [[Option<Rc<dyn Piece>>; SIZE]; SIZE]
Incidentally, this is representing a chess board, and Piece is a trait, so if there is a better way to store this data, I would be interested.
I am having difficulty initializing this array. The obvious solution, setting everything to None:
board: [[None; SIZE]; SIZE]
doesn't work because
error[E0277]: the trait bound `std::rc::Rc<(dyn piece::Piece + 'static)>: std::marker::Copy` is not satisfied
--> src/chessboard.rs:17:21
|
17 | board: [[None; SIZE]; SIZE]
| ^^^^^^^^^^^^ the trait `std::marker::Copy` is not implemented for `std::rc::Rc<(dyn piece::Piece + 'static)>`
|
= note: required because of the requirements on the impl of `std::marker::Copy` for `std::option::Option<std::rc::Rc<(dyn piece::Piece + 'static)>>`
= note: the `Copy` trait is required because the repeated element will be copied
Some research led me to this github issue on the topic, https://github.com/rust-lang/rust/issues/54542, where there seems to be some disagreement about the topic, though most solutions appear to use MaybeUninit and unsafe rust to create the array in memory, iterate over it to initialize it, then either mem::transmute or into_inner it into the regular array. Because I am not very familiar with unsafe rust or dealing with memory, I'd rather not use these solutions, and am not entirely certain how to adapt those solutions, which are for [Vec<u8>; N] to my use case.
I found another article on the subject, https://www.joshmcguigan.com/blog/array-initialization-rust/, which presents a crate with a macro, arr! which is supposed to be entirely safe. However, I am also not certain if this is the most idiomatic and clean solution. Having to install an entire crate for such a small thing seems excessive (though that may be my feelings from languages, as I don't know much about the best practices in Rust).
Which, if either, of these solutions should I use, and if it is the former, how should I adapt it to arrays of arrays?