Update
This can work:
let array: [T; N] = something_iterable.[into_]iter() .collect::<Vec<T>>() .try_into() .unwrap()
In newer version of rust, try_into is included in prelude, so it is not necessary to use std::convert::TryInto. Further, starting from 1.48.0, array support directly convert from Vec type, signature from stdlib source:
fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> { ... }
Original Answer
as of rustc 1.42.0, if your element impl Copy trait, for simplicity, this just works:
use std::convert::TryInto; ... let array: [T; N] = something_iterable.[into_]iter() .collect::<Vec<T>>() .as_slice() .try_into() .unwrap()
collect as_slice try_into + unwrap() Iterator<T> ------> Vec<T> -------> &[T] ------------------> [T]
But I would just call it a workaround. You need to include std::convert::TryInto because the try_into method is defined in the TryInto trait.
Below is the signature checked when you call try_into as above, taken from the source. As you can see, that requires your type T implement Copy trait, so theoritically, it will copy all your elements once.
#[stable(feature = "try_from", since = "1.34.0")] impl<T, const N: usize> TryFrom<&[T]> for [T; N] where T: Copy, [T; N]: LengthAtMost32, { type Error = TryFromSliceError; fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> { <&Self>::try_from(slice).map(|r| *r) } }
array.mapwith current Rust, see my answer for an example.