Trait implements Iterator, but cannot use a structure that implements my trait as Iterator

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

/// A generic trait for reading u32s
trait MyReader {
    fn get_next(&mut self) -> Option<u32>;
}

/// Which means we should be able to iterate over the reader, yielding u32s
impl Iterator for MyReader {
    type Item = u32;
    fn next(&mut self) -> Option<u32> {
        self.get_next()
    }
}

/// Example of a 'reader'
struct MyVec {
    buffer: Vec<u32>,
}

/// This can act as a reader
impl MyReader for MyVec {
    fn get_next(&mut self) -> Option<u32> {
        self.buffer.pop()
    }
}

fn main() {
    // Create a reader
    let mut veccy = MyVec { buffer: vec![1, 2, 3, 4, 5] };

    // Doesn't work :(
    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 , , .

+4
1

, .

impl Iterator for MyReader {

Iterator MyReader. Iterator , MyReader. , - .

Rust , , , , . ( , .) Iterator , , t . , , , Iterator - ?

, , MyReader newtype, Iterator. , Iterator .

+4

Source: https://habr.com/ru/post/1668972/


All Articles