简体   繁体   中英

How to implement iterator using trait

I have a struct called Library, which has a vector of strings (titles). I have implemented an iterator for this. Here is my code.

#[derive(Debug, Clone)]
struct Library {
    books: Vec<String>
}

impl Iterator for Library {
    fn next(&mut self) -> Option<Self::Item> {
        ...
    }
}

Now, I am trying to implement an Iterator using a trait, like this:

fn foo(x: Vec<u32>) -> impl Iterator<Item=u32> {
    //Unsure if correct method
    fn next() -> Option<...> {
       x.into_iter()....

    }
}

But I'm unsure of how to proceed in this case. Do I simply have to define a next() method again? That doesn't seem to be the case, according to other resources. Why is that? Shouldn't an iterator (which is being returned) have a next() method?

What is the general method for implementing an iterator this way?

You wouldn't implement the trait directly on Library . The library is not an iterator, but it is something that could be iterated by an iterator.

Instead, just declare a method that returns an iterator, and you can simply return an iterator directly from your vector. There is no need for a custom iterator implementation. For example:

impl Library {
    fn iter(&self) -> impl Iterator<Item=&String> {
        self.books.iter()
    }
}

For your second case, you can turn the vector into an iterator using into_iter() , provided by the IntoIterator trait:

fn foo(x: Vec<u32>) -> impl Iterator<Item=u32> {
    x.into_iter()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM