Bounding an impl Iterator<> so I can borrow self inside a Map closure

Hello,

Sorry in advance for the dumb question. This feels like it should be possible but I can't figure out the right way to bound the returned object so it can compile.

Any help is very much appreciated.

struct MyContainer {
    records : Vec<String>
}

struct MyElementPointer<'a> {
    container : &'a MyContainer,
    record : &'a String
}

impl MyContainer {
    pub fn iter<'incoming>(&'incoming self) -> impl Iterator<Item=MyElementPointer<'incoming>> + 'incoming {
        self.records.iter().map(|record| MyElementPointer{container : &self, record : record})
    }
}

fn main() {
    let my_container = MyContainer{records : vec!["one".to_string(), "two".to_string(), "three".to_string()]};
    
    for pointer in my_container.iter() {
        println!("{} of {}", pointer.record, pointer.container.records.len());
    }
}

Thank you in advance.

FIxed it by replacing .map(|record| with .map(move|record|
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9bb0de51d1ccb7fd839a53bba1dbc4cd

1 Like

Thanks for the reply.

I thought, however, that this would make an owned copy of the container, effectively copying the whole container and every element in it, for every single iteration?

Am I misunderstanding the way the move directive works?

move moves the variables it uses, it just copies the self reference here(not the value it points to, the reference itself).
Without the move it stores a &&'incoming MyContainer in the closure, which is only valid inside the method.

1 Like

Ahhh. That was my misunderstanding. Thanks!

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.