pub trait Defaults<T> {
// Required method
fn defaults() -> T
where Self: Default;
}Expand description
Create a ‘default’ container type T with N instances of Self.
Used when we need a collection of default type instances
e.g. when creating a default bank we need 16 default patterns.
Using the ot_tools_io_derive::DefaultsAsArray, DefaultsAsArrayBoxed proc_macro will automatically derive
implementations for
T: [Self; N]T: Box<serde_big_array::Array<Self, N>>
If you need to handle incrementing id fields, see the existing examples for the following types
crate::patterns::AudioTrackTrigs,crate::patterns::MidiTrackTrigs,crate::parts::Partcrate::parts::AudioTrackMachineSlot
use std::array::from_fn;
use serde_big_array::Array;
use ot_tools_io::Defaults;
struct SomeType {
x: u8,
}
impl Default for SomeType {
fn default() -> Self {
Self { x: 0 }
}
}
impl<const N: usize> Defaults<[SomeType; N]> for SomeType {
fn defaults() -> [Self; N] where Self: Default {
from_fn(|_| Self::default())
}
}
impl<const N: usize> Defaults<Box<Array<SomeType, N>>> for SomeType {
fn defaults() -> Box<Array<Self, N>> where Self: Defaults<[Self; N]> {
Box::new(Array(
// use the [Self; N] impl to generate values
<Self as Defaults<[Self; N]>>::defaults()
))
}
}
impl<const N: usize> Defaults<Array<SomeType, N>> for SomeType {
fn defaults() -> Array<Self, N> where Self: Defaults<[Self; N]> {
Array(
// use the [Self; N] impl to generate values
<Self as Defaults<[Self; N]>>::defaults()
)
}
}
let xs: [SomeType; 20] = SomeType::defaults();
assert_eq!(xs.len(), 20);
let xs: [SomeType; 25] = SomeType::defaults();
assert_eq!(xs.len(), 25);
let xs: Box<Array<SomeType, 20>> = SomeType::defaults();
assert_eq!(xs.len(), 20);
let xs: Box<Array<SomeType, 25>> = SomeType::defaults();
assert_eq!(xs.len(), 25);
let xs: Array<SomeType, 20> = SomeType::defaults();
assert_eq!(xs.len(), 20);
let xs: Array<SomeType, 25> = SomeType::defaults();
assert_eq!(xs.len(), 25);