1

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.

2
  • What do you want to initialize it to? Default values? A specific array? Commented Apr 5, 2020 at 0:51
  • Something like [33; N], for example. Commented Apr 5, 2020 at 1:52

1 Answer 1

3

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.