2d Iterator Map Function

⚓ Rust    📅 2025-06-23    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 50 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: 2d Iterator Map Function

Hi, I'm struggling a little with writing the following 'custom map' function. I have a 2d Vector (Vec<Vec<T>>) and I would like to Map this into a "2d" Iterator, so basically an iterator of iterators.

My basic function does the same, but concretises the values immediately into a Vec<Vec<O>>:

fn map2d<T, O, F: FnMut(&T) -> O>(data: &Vec<Vec<O>>, mut f: F) -> Vec<Vec<O>> {
    data.iter().map(|l| l.iter().map(|n| f(n).collect()).collect()
}

And this of course works. However, against better judgement, I let curiosity get the better of me and tried (and eventually failed) to come up with a solution that would allow returning such a 2d iterator. The following is what I came up with after following the compiler hints, but the core issue is that the f is captured and then moved.

fn map2d<'a, T, O, F: FnMut(&T) -> O + 'static>(
    data: &'a Vec<Vec<T>>,
    mut f: F,
) -> impl Iterator<Item = impl Iterator<Item = O> + use<'a, T, O, F>> {
    data.iter().map(move |l| l.iter().map(move |n| f(n)))
}

Is this at all something that can be implemented like this? I also tried a "Custom" iterator structure, implementing Iterator, but this of course falls into the same pitfall.

3 posts - 3 participants

Read full topic

🏷️ rust_feed