rustiterator

How to get rid of extraneous (0..) in iteration when its not used?


I came up with the following function to transpose a Vec<Vec<T>>:

fn transpose<T>(v: Vec<Vec<T>>) -> Vec<Vec<T>> {
    let mut xs = v.into_iter().map(|x| x.into_iter()).collect::<Vec<_>>();
    (0..)
        .map_while(|_| xs.iter_mut().map(|x| x.next()).collect())
        .collect()
}

The values of (0..) are unused but anchors the iterator. I can put anything there. But can it be restructured to not have a useless iterator there?


Solution

  • You can use std::iter::from_fn:

    Creates a new iterator where each iteration calls the provided closure F: FnMut() -> Option<T>.

    fn transpose<T>(v: Vec<Vec<T>>) -> Vec<Vec<T>> {
        let mut xs = v.into_iter().map(|x| x.into_iter()).collect::<Vec<_>>();
        std::iter::from_fn(|| xs.iter_mut().map(|x| x.next()).collect()).collect()
    }