I use the generic-array crate:
struct Foo<N: ArrayLength<i32>> {
data: GenericArray<i32, N>
}
But it doesn't explain how to initialize value:
impl<N: ArrayLength<i32>> Foo<N> {
pub fn new() -> Self {
Self {
data: // What to puts here?
}
}
}
Playground here to help testers.
You can default-initialize and mutate them afterwards:
let mut data = GenericArray::default();
for x in &mut data {
*x = 33;
}
Or you can use the GenericArray::from_exact_iter
function. The problem is that there does not seem to be an easy way to create an iterator of n
elements that also implements ExactSizeIterator
. You can implement one though:
struct RepeatN<T>{
item: T,
count: usize,
}
impl<T: Clone> Iterator for RepeatN<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
self.count.checked_sub(1).map(|count| {
self.count = count;
self.item.clone()
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.count, Some(self.count))
}
}
impl<T: Clone> ExactSizeIterator for RepeatN<T> {
fn len(&self) -> usize {
self.count
}
}
fn repeat_n<T: Clone>(item: T, count: usize) -> RepeatN<T> {
RepeatN {
item,
count,
}
}
And use it like GenericArray::from_exact_iter(repeat_n(33, N::to_usize())).unwrap()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.