0

I'm implementing the trait Vector. This trait has several methods including iter which returns an iterator.

pub trait Vector<T, I: Iterator<Item = T>> {
    // several functions
    fn iter(&self) -> I;
}

VectorImplementation1 implements Vector:

pub struct VectorImplementation1<T, I: Iterator> {
    numbers: Vec<T>,
    phantom: std::marker::PhantomData<I>, //otherwise error because I not used
}

impl<T, I: Iterator<Item = T>> VectorImplementation1<T, I> {
    // constructor
}

impl<T, I: Iterator<Item = T>> Vector<T, I> for VectorImplementation1<T, I> {
    // several functions
    fn iter(&self) -> I {
        self.numbers.iter()
    }
}

The compiler returns an error:

error[E0308]: mismatched types
  --> src/lib.rs:18:9
   |
17 |     fn iter(&self) -> I {
   |                       - expected `I` because of return type
18 |         self.numbers.iter()
   |         ^^^^^^^^^^^^^^^^^^^ expected type parameter, found struct `std::slice::Iter`
   |
   = note: expected type `I`
              found type `std::slice::Iter<'_, T>`

Apparently std::slice::Iter (the type returned by iter) doesn't implement Iterator.

What trait can I use if I can't use Iterator? Must I do something different?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    This seems like a mix-up between a trait's parameter types and a trait's associated types. You would want the type `I` to be an associated type instead, but even after that you would be facing the [streaming iterator problem](https://stackoverflow.com/q/30422177/1233251). – E_net4 Apr 13 '19 at 20:57
  • I believe your question is answered by the answers of [How do I implement a trait with a generic method?](https://stackoverflow.com/q/53085270/155423) and [How do I write an iterator that returns references to itself?](https://stackoverflow.com/q/30422177/155423). If you disagree, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Apr 13 '19 at 21:25
  • 1
    [The duplicate applied to your case](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e68cafe17009e59a39172054802b2935). You may also be interested in [`IntoIterator`](https://doc.rust-lang.org/std/iter/trait.IntoIterator.html) – Shepmaster Apr 13 '19 at 22:48

0 Answers0