我有一个Vec<Box<T>>地方T器具Foo.为什么我不能强迫它到Vec<Box<Foo>>即使我可以强迫型的东西Box<T>成Box<Foo>?为什么以下代码无法编译?
use std::vec;
trait Foo {}
struct Bar {}
impl Foo for Bar {}
fn main() {
let v = vec![Box::new(Bar {})];
let v_1 = v as Vec<Box<Foo>>;
}
Run Code Online (Sandbox Code Playgroud) 我有一个struct对象的集合.我想用特征对象的迭代器迭代集合,但是我不能为它创建一个合适的迭代器.我减少的测试代码是:
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())
}
}
Run Code Online (Sandbox Code Playgroud)
这会导致以下编译器错误:
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
| …Run Code Online (Sandbox Code Playgroud)