如何循环盒装迭代器?

awe*_*kie 7 rust rust-obsolete

注意:自Rust 1.0以来,这个问题已经过时了.该Iterator特征现在具有关联类型,Item而不是类型参数,Iterator并添加了一个毯子实现Box<Iterator>.

我想定义一个返回迭代器的trait方法.我想避免指定实际的返回类型,所以在我们有未装箱的抽象返回类型之前,我正在使用特征对象.这意味着该方法返回Box<Iterator<A>>.但我不知道如何使用盒装特质对象.我无法迭代类型的对象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 {}
}
Run Code Online (Sandbox Code Playgroud)

这个错误"for" loop expression does not implement the "Iterator" trait.

所以我的问题是:我怎样才能迭代Box<Iterator<A>>.或者,更一般地说,我如何使用盒装特征对象?

Bur*_*hi5 5

问题是Box<Iterator<A>>本身并没有实现这一Iterator特性.(我不确定为什么,也许其他人可以在这一点上插话.)

您可以自己解决这个问题:

impl<A> Iterator<A> for Box<Iterator<A>> {
    fn next(&mut self) -> Option<A> { self.next() }
}
Run Code Online (Sandbox Code Playgroud)

但由于您的箱子中既没有定义类型也没有特征,因此不允许这样做.要解决这个问题,您可以定义自己的子特性Iterator,Iterator<A>为所有人Box<MyIter<A>>实现,然后MyIter<A>I满足以下条件的所有类型实现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() }
}
Run Code Online (Sandbox Code Playgroud)

而且您必须更改要使用的代码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); }
}
Run Code Online (Sandbox Code Playgroud)

(我添加了可变性,boxed_iter因为它是迭代器所必需的.)

  • 这是因为代码有点腐烂.因为`Box <Iterator>`impl`Iterator`,这个问题应该不再适用了. (2认同)