Note: This question is obsolete since Rust 1.0. The
Iterator
trait now has an associated type,Item
, instead of a type parameter and a blanketIterator
implementation was added forBox<Iterator>
.
我想定义一个返回迭代器的特征方法。我想避免指定实际的返回类型是什么,所以在我们有未装箱的抽象返回类型之前,我一直在使用特征对象。这意味着该方法返回 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 {}
}
此错误与 "for" loop expression does not implement the "Iterator" trait
.
所以我的问题是:如何遍历 Box<Iterator<A>>
.或者,更一般地说,我如何使用盒装特征对象?
最佳答案
问题是 Box<Iterator<A>>
本身不实现 Iterator
特征。 (我不确定确切原因,也许其他人可以在这一点上插话。)
你可以自己解决这个问题:
impl<A> Iterator<A> for Box<Iterator<A>> {
fn next(&mut self) -> Option<A> { self.next() }
}
但是由于您的 crate 中既没有定义类型也没有定义特征,所以这是不允许的。要解决此问题,您可以定义自己的子特征 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() }
}
而且您必须更改代码才能使用 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
添加了可变性,因为它是迭代器所必需的。)
关于rust - 如何遍历盒装迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25436356/