如何循环遍历装箱迭代器?

7
注意:自Rust 1.0以来,此问题已过时。现在,Iterator特质拥有一个关联类型Item,而不是类型参数,并且添加了一个适用于Box 的通用Iterator实现。
我想定义一个返回迭代器的特质方法。我想避免具体指定实际返回类型,因此在我们拥有未打包的抽象返回类型之前,我使用特质对象。这意味着该方法返回Box >类型。但是我不知道如何使用打包的特质对象。我无法迭代Box >类型的对象。
fn main() {
    let xs = vec![0u, 1, 2, 3];
    let boxed_iter = box xs.iter() as Box<Iterator<&uint>>;
    for x in boxed_iter {}
}

出现了错误:"for" loop expression does not implement the "Iterator" trait

我的问题是:如何迭代 Box<Iterator<A>>。或者更普遍地说,如何使用盒式特征对象?

1个回答

5
问题在于 Box<Iterator<A>> 本身没有实现 Iterator 特质。(我不确定为什么,或许其他人可以对此发表意见。)
你可以通过以下方式自己解决这个问题:
impl<A> Iterator<A> for Box<Iterator<A>> {
    fn next(&mut self) -> Option<A> { self.next() }
}

但是,由于你的箱子中没有定义类型或特征,所以这是不允许的。为了解决这个问题,您可以定义自己的Iterator的子特征,为所有Box<MyIter<A>>实现Iterator<A>,然后为所有满足Iterator<A>的类型I实现MyIter<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() }
}

您需要更改代码,使用 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); }
}

(由于迭代器需要可变性,因此我在 boxed_iter 中添加了可变性。)

以下错误导致代码无法编译:lib.rs:9:19: 9:30 错误:类型参数数量错误:期望 0,实际上是 1 [E0244] lib.rs:9 trait MyIter<A> : Iterator<A> {} ^~~~~~~~~~~ lib.rs:9:19: 9:30 帮助:运行 rustc --explain E0244 查看详细解释 lib.rs:10:12: 10:23 错误:类型参数数量错误:期望 0,实际上是 1 [E0244] lib.rs:10 impl<A, I: Iterator<A>> MyIter<A> for I {} ^~~~~~~~~~~ - NBcode
lib.rs:10:12: 10:23 提示:运行 rustc --explain E0244 查看详细解释 lib.rs:13:29: 13:38 错误:必须指定关联类型 Item(来自 trait core::iter::Iterator)的值 [E0191] lib.rs:13 impl<A> Iterator<A> for Box<MyIter<A>> { ^~~~~~~~~ lib.rs:13:9: 13:20 错误:类型参数数量错误:期望 0,发现 1 [E0244] lib.rs:13 impl<A> Iterator<A> for Box<MyIter<A>> { ^~~~~~~~~~~ - NBcode
3
因为代码已经陈旧过时了。由于Box<Iterator>实现了Iterator,所以这个问题不再相关。 - BurntSushi5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接