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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With