【发布时间】:2019-10-23 01:30:32
【问题描述】:
我有一个 trait,它包含一个函数来返回一个迭代器,而不是对另一个 trait 的引用,例如:
pub trait ParentInterface {
fn children<'a>(&'a self) -> Box<dyn Iterator<Item = &'a ChildInterface>>;
}
pub trait ChildInterface {
fn some_method(&self) -> bool;
}
在为存储具体值向量的具体类型实现此特征时,如何返回正确类型的迭代器?
pub struct ConcreteParent {
my_children: Vec<ConcreteChild>,
}
pub struct ConcreteChild {
my_value: bool,
}
impl ParentInterface for ConcreteParent {
fn children<'a>(&'a self) -> Box<dyn Iterator<Item = &'a ChildInterface>> {
Box::new(self.my_children.iter()) // Compiler error!
}
}
impl ChildInterface for ConcreteChild {
fn some_method(&self) -> bool {
self.my_value
}
}
上面的例子产生了 Rust 2018 的编译器错误:
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, ConcreteChild> as std::iter::Iterator>::Item == &dyn ChildInterface`
--> src/lib.rs:19:9
|
19 | Box::new(self.my_children.iter()) // Compiler error!
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `ConcreteChild`, found trait ChildInterface
|
= note: expected type `&ConcreteChild`
found type `&dyn ChildInterface`
= note: required for the cast to the object type `dyn std::iter::Iterator<Item = &dyn ChildInterface>`
我假设 my_children.iter() 返回一个带有错误 Item 类型(具体类型而不是 trait 类型)的迭代器 - 如何解决这个问题?
【问题讨论】:
标签: reference rust iterator traits