Home > Software engineering >  Rust: Re-exposing an into_iter implementation with generics?
Rust: Re-exposing an into_iter implementation with generics?

Time:12-06

I'm trying in rust to extend the VecDeque class to drop elements after a max capacity. There's probably something that already does this, but I'm stubborn, am relatively new to rust, and want to know the right way to do this. However, I'm getting stuck on implementing the IntoIterator with the generics and am getting an error I don't understand.

 struct SlidingQueue<T> {
    data: VecDeque<T>,
    max_capacity: usize,
 }

 impl<T> SlidingQueue<T> {
//...
 }

 // just re-expose the VecDeque::IntoIter 
 impl<T> IntoIterator for SlidingQueue<T> {
    type Item=T;

    // type IntoIter=VecDeque<Self::Item>::IntoIter;
    type IntoIter: = VecDeque<T>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.data.into_iter()
    }
}

This produces:

error[E0223]: ambiguous associated type
  --> src\sliding_queue.rs:32:22
   |
32 |     type IntoIter: = VecDeque<T>::IntoIter;
   |                      ^^^^^^^^^^^^^^^^^^^^^ help: use fully-qualified syntax: `<VecDeque<T> as Trait>::IntoIter`

The rustc --explain E0223 explainer seems to indicate I'm referencing an undefined type in a trait... but I don't think that's true. My attempts to do what the compiler suggests also fail (what trait is 'Trait'?). Any suggestions would be apprecaited!

CodePudding user response:

The compiler just tells you that it doesn't know where VecDeque<T>::IntoIter comes from.

It can come from the implementation of IntoIterator for VecDeque<T>, but it can also potentially come from some different trait implementation that also has an associated type named IntoIter.

So you need to tell the compile which trait to take the associated type from, using fully-qualified path:

type IntoIter = <VecDeque<T> as IntoIterator>::IntoIter;

Or just follow the documentation that tells us that this type is named std::collections::vec_deque::IntoIter:

type IntoIter = std::collections::vec_deque::IntoIter<T>;
  • Related