How to iterate over an iterator with a box?

Note: This question has been deprecated after Rust 1.0. The Iterator attribute now has an associated Item type instead of a type parameter, and an Box<Iterator> style implementation has been added for Box<Iterator> .

I want to define a trait method that the iterator returns. I want to not indicate what the actual type of the return value is, so until we use the abstract types of return messages, I use feature objects. This means that the method returns Box<Iterator<A>> . But I'm not sure how to use the object with boxes. I cannot iterate over an object like Box<Iterator<A>> :

 fn main() { let xs = vec![0u, 1, 2, 3]; let boxed_iter = box xs.iter() as Box<Iterator<&uint>>; for x in boxed_iter {} } 

These errors with the "for" loop expression does not implement the "Iterator" trait .

So my question is: how can I iterate over Box<Iterator<A>> . Or, more generally, how can I use objects with boxes?

+6
source share
1 answer

The problem is that Box<Iterator<A>> itself does not implement the Iterator trait. (I don’t know exactly why, maybe someone else can call back at this moment.)

You can fix it yourself:

 impl<A> Iterator<A> for Box<Iterator<A>> { fn next(&mut self) -> Option<A> { self.next() } } 

But since neither type nor trait is defined in your box, this is unacceptable. To get around this, you could define your own Iterator attribute, implement Iterator<A> for all Box<MyIter<A>> , and then implement MyIter<A> for all I types that satisfy Iterator<A> :

 trait MyIter<A> : Iterator<A> {} impl<A, I: Iterator<A>> MyIter<A> for I {} // This is now allowed because `MyIter` is defined in this crate. impl<A> Iterator<A> for Box<MyIter<A>> { fn next(&mut self) -> Option<A> { self.next() } } 

And you have to change your code to use as Box<MyIter<&uint>> :

 fn main() { let xs = vec![0u, 1, 2, 3]; let mut boxed_iter = box xs.iter() as Box<MyIter<&uint>>; for x in boxed_iter { println!("{}", x); } } 

(I added variability to boxed_iter , as this is required for iterators.)

+5
source

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


All Articles