Iterator flat_map

I'm a rust newbe trying to use flat_map on an iterator and i'm a bit lost on the error message here.
Could someone help me understand what i'm doing wrong?
I simplified to the maximum, but the point of "mux" would be to filter/split S into 0 or more instances of S. Applying this, i want to create a new iterator of S from an original iterator of S.

struct S {
    i: i32,

fn mux() -> impl Fn(&S) -> Vec<&S> {
    |s: &S| vec![s.clone()]

fn run(iter: impl Iterator<Item = S>) -> impl Iterator<Item = S> {


The closure given to flat_map takes the input by value, not as a reference. Try this.

Note also that your return value is Vec<&S>, but you clone the s, so you're actually returning an Vec<S>.

References are not the same as values.

1 Like

Thanks for the quick reply Alice :slight_smile:
Returning Vec<&S> was indeed a mistake.
But what I'm really trying to do is to have a bunch of "mux" functions and generate several different iterators from the initial one, hence my trying to not consume S but pass it as reference (read only).
Or does it mean i must first clone the iterator before applying a transformation?

.. forget the last part, i'll try itertools' tee or something, but you pointed me to the primary issue that flat_map requires to consume the item. Thanks.

Many Iterator methods work by a closure taking ownership of an item, and giving it back after doing something to it. You can think of it as a pipe of sorts.

If you just want to look at an item, you can use the inspect method on iterators.