Building arrays from iterators


It should be easy/trivial to build arrays from iterators, and panic if the iterator is too long or too short.

A pseudocode from_iterator would just look like:

fn from_iterator(foo) -> [T; N] {
    let a =;
    let b =;
    let c =;
    let d =;
    assert_eq!(, None);
    [a, b, c, d]
1 Like

If we had const generics, a recursive solution would have to be used instead. We’d just need to make sure the compiler can de-recurse it.


It seems to me like with const generics, fixed-sized arrays should be able to impl FromIterator ala the method you have above.

That said, it’d be nice if there was a solution to avoid panicking too, e.g. doing collect() on Option<[T; N]> which returned None if there is a length mismatch.


I think that the recently stabilized TryFrom trait will be a better fit.

BTW I am still not quite sure why we have FromIterator trait. Why collect can’t use B: From<Self> bound instead of B: FromIterator<Self::Item>? Is there some complexity issues due to the coherency rules? Or was it done only for symmetry with IntoIterator (which also may be considered redundant, but makes for loop integration much nicier)?

1 Like

next could panic, need recursion


It can deal with panics by wrapping the incomplete array in ManuallyDrop and a newtype to drop whatever was already written.


You can always just collect into an arrayvec and into_inner the array out. That way all the special cases are already handled.

(And maybe you’ll find that you’re fine with just an arrayvec anyway.)


well, this is my use-case:

so. yeah. idk. I’d rather just have a built-in from_iterator for arrays. as we should, anyway (IMO).