How to efficiently collect an iterator of arbitrary length into an array of fixed length?

I want to collect a lazy iterator with expensive operations and arbitrary length into a fixed-length array without wasting resources on redundant (remaining) elements. I've tried this but it doesn't compile:

let my_array = my_vec
    .map(expensive_operation) // only maximum of 3 calls should be allowed
    .collect::<Result<[String; 3], _>>() // returns Ok(_) if my_vec.len() ≥ 3
    .expect("insufficient number of elements");

You should use the take method from Iterator.


You might also want to look how Itertools::collect_tuple is implemented - yes, that's tuple, not array, but your own implementation for array could be similar.

1 Like

Right now, the best way is to collect into an ArrayVec — data structures in Rust //, then use to get the array out.

1 Like