Appearance
Say you have the following struct:
rust
struct MyStruct {
arr: [Option<MyType>; 8],
}
Now, the challenge is to implement the Default
trait, given that Option
doesn’t implement the Copy
trait.
IMPORTANT
The Copy
trait is necessary for using the array initialization syntax, like [None; N]
.
Solution: Mapping to Option<T>
You can resolve this by mapping an array to Option<T>
, like so:
rust
impl Default for MyStruct {
fn default() -> Self {
Self {
// `[None; N]` requires that `Some(T)` is `Copy`able
arr: [0; 8].map(|_| None),
}
}
}
Alternative Approach
If working with Option<T>
becomes cumbersome, particularly when dealing with types that aren’t Clone
or Copy
, you can initialize a custom array as follows:
rust
pub struct MyStruct<const N: usize> {
// `Wavetable` does not implement `Clone` nor `Copy`
voices: [Wavetable; N],
}
impl<const N: usize> MyStruct<N> {
pub fn new(sample_rate: usize) -> Self {
let voices = [(); N].map(|_| Wavetable::new(sample_rate));
Self { voices }
}
}
This approach gives you more flexibility when dealing with non-Clone
and non-Copy
types, especially when custom initialization logic is required.