How to wrap an inner iterator created from the ref of the temporary variable from another iterator

So recently i've stumbled upon a pattern in rust and i want to make some optimizations on it so that i can simplify my codes. Here's the psuedocode.

for foo in fooIter {
    for bar in foo.iter() {
         // do something on the bar.
    }
}

Her BarIter borrows foo so that it can yield some data structures that are constructed from the borrowed inner fields of foo because foo is a container.

What i'm trying to achieve here is to merge these two loops into one for something like.

fooIter.transform_into_other_iter_from_foo()

Here foo must be an owned type not an reference to some other types sadly.
Another constrait is that FooIter is not a collection of foos instead it only construcst a foo and does not hold it because its len cannot be determined.

My question is how to merge this two loops. Because i got a struct capable of yielding FooIter and it's really helpful if i can also yield BarIter or some other Iters based on this method which can help me save a lot works from writing this burdonsome pattern. Or is it simply unachievable? Thanks :slight_smile:

Sounds like you are looking for Iterator::flatten?

4 Likes

yeah, but i guess that's the same as if i use a collect method and then use a iter + flatmap.

However, this introduces heap allocation.

No, it's lazy and doesn't allocate (is defined in core).

2 Likes

Why?

Guessing is a terrible way to reason about performance, by the way. At the very minimum, you should be reading the documentation and the code of the implementation, and definitely not just assume things.


By the way, iterator adapters are by convention lazy and try to avoid allocating to the greatest extent possible; when it's not possible, they'll document the fact (and in general, the performance characteristics will be very clearly laid out in doc comments).

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.