如何迭代结构集作为特征对象引用的迭代器? [英] How to iterate over a collection of structs as an iterator of trait object references?
问题描述
我有一个struct对象集合.我想用特征对象的迭代器遍历集合,但是我不能为此创建合适的迭代器.我减少的测试代码是:
I have a collection of struct objects. I'd like to iterate over the collection with an iterator of trait objects, but I can't create an appropriate iterator for that. My reduced test code is:
struct MyStruct {}
struct MyStorage(Vec<MyStruct>);
trait MyTrait {} // Dummy trait to demonstrate the problem
impl MyTrait for MyStruct {}
trait MyContainer {
fn items<'a>(&'a self) -> Box<Iterator<Item = &'a MyTrait> + 'a>;
}
impl MyContainer for MyStorage {
fn items<'a>(&'a self) -> Box<Iterator<Item = &'a MyTrait> + 'a> {
Box::new(self.0.iter())
}
}
这将导致以下编译器错误:
This results the following compiler error:
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, MyStruct> as std::iter::Iterator>::Item == &MyTrait`
--> src/main.rs:12:9
|
12 | Box::new(self.0.iter())
| ^^^^^^^^^^^^^^^^^^^^^^^ expected struct `MyStruct`, found trait MyTrait
|
= note: expected type `&MyStruct`
found type `&MyTrait`
= note: required for the cast to the object type `std::iter::Iterator<Item=&MyTrait>`
我的理解是,尽管&MyStruct
通常可以转换为&MyTrait
,但是在这种情况下,标准库的Iterator
实现不允许它.
请注意,相同的构造适用于Vec<Box<MyStruct>>
和Iterator<Item=&Box<MyTrait>>
,但是这里不需要装箱.
My understanding is that though &MyStruct
is normally convertible to &MyTrait
, the Iterator
implementation of the standard library doesn't allow it in this case.
Note that the same construct works with a Vec<Box<MyStruct>>
and Iterator<Item=&Box<MyTrait>>
, but boxing doesn't feel necessary here.
有什么办法可以使引用工作吗?
Is there any way to make this work with references?
推荐答案
您需要显式转换单个元素,如下所示:
You need to cast the single elements explicitly, like this:
Box::new(self.0.iter().map(|e| e as &MyTrait))
这篇关于如何迭代结构集作为特征对象引用的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!