我正在实现特征Vector
。此特征有几种方法,包括iter
,它返回一个迭代器。
pub trait Vector<T, I: Iterator<Item = T>> {
// several functions
fn iter(&self) -> I;
}
VectorImplementation1
实现Vector
:
pub struct VectorImplementation1<T, I: Iterator> {
numbers: Vec<T>,
phantom: std::marker::PhantomData<I>, //otherwise error because I not used
}
impl<T, I: Iterator<Item = T>> VectorImplementation1<T, I> {
// constructor
}
impl<T, I: Iterator<Item = T>> Vector<T, I> for VectorImplementation1<T, I> {
// several functions
fn iter(&self) -> I {
self.numbers.iter()
}
}
编译器返回错误:
error[E0308]: mismatched types
--> src/lib.rs:18:9
|
17 | fn iter(&self) -> I {
| - expected `I` because of return type
18 | self.numbers.iter()
| ^^^^^^^^^^^^^^^^^^^ expected type parameter, found struct `std::slice::Iter`
|
= note: expected type `I`
found type `std::slice::Iter<'_, T>`
显然std::slice::Iter
(iter
返回的类型)没有实现Iterator
。
如果我不能使用Iterator
,该如何使用?我必须做点别的事情吗?