iterate over the inner field in a structural way

There are a couple changes that you have to make:

struct Wrapper {
    pub items: Vec<String>
}

struct IterWrapper<'a> {
    // this needs to own the iterator, not a reference to it
    // in order to avoid returning a borrowed value
    inner: std::slice::Iter<'a, String>,
}

impl<'a> Iterator for IterWrapper<'a> {
    type Item = &'a String;

    fn next(&mut self) -> Option<Self::Item> {
        // no semicolon here so the result is implicitly returned
        // your old error happened because the semicolon causes the value to not be returned
        self.inner.next()
    }
}

impl Wrapper {
    fn iter<'a>(&'a self) -> IterWrapper<'a> {
        IterWrapper {
            // give the iterator, not the reference to it
            inner: self.items.iter(),
        }
    }
}

fn main() {
    
    let w = Wrapper {
        items: vec![String::from("test1"), String::from("test2")]
    };

    for item in w.iter() {
        println!("{}", item);
    }

}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top