I have a trait, and I want to say that if a structure implements this trait, it can also act like Iterator. However, I get a compiler error when trying to use struct as an iterator.
I am writing a library to read the same type of data from different file formats. I want to create a common βreaderβ trait that will return the correct rust objects. I want to say that every reader can work as an Iterator, giving way to this object.
Here is the code
trait MyReader {
fn get_next(&mut self) -> Option<u32>;
}
impl Iterator for MyReader {
type Item = u32;
fn next(&mut self) -> Option<u32> {
self.get_next()
}
}
struct MyVec {
buffer: Vec<u32>,
}
impl MyReader for MyVec {
fn get_next(&mut self) -> Option<u32> {
self.buffer.pop()
}
}
fn main() {
let mut veccy = MyVec { buffer: vec![1, 2, 3, 4, 5] };
let res = veccy.next();
}
Compiler Output:
rustc 1.15.0 (10893a9a3 2017-01-19)
error: no method named `next` found for type `MyVec` in the current scope
--> <anon>:31:21
|
31 | let res = veccy.next();
| ^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope; the following traits define an item `next`, perhaps you need to implement one of them:
= help: candidate #1: `std::iter::Iterator`
= help: candidate #2: `std::iter::ZipImpl`
= help: candidate #3: `std::str::pattern::Searcher`
Here is the code on the rust pad.
, MyVec MyReader, , .next() . MyReader, Iterator , ? impl Iterator for ... , Iterator , , .