我觉得这段代码应该可以工作,因为在大多数情况下,Box<Dog>
应该能够隐式转换为 Box<dyn Animal>
:
struct Dog {}
trait Animal {}
impl Animal for Dog {}
fn main() {
let _: Vec<Box<dyn Animal>> = [Dog {}, Dog {}]
.into_iter()
.map(Box::new)
.collect();
}
然而,我收到了以下编译器错误:
error[E0277]: a value of type `Vec<Box<dyn Animal>>` cannot be built from an iterator over elements of type `Box<Dog>`
--> src/main.rs:9:10
|
9 | .collect();
| ^^^^^^^ value of type `Vec<Box<dyn Animal>>` cannot be built from `std::iter::Iterator<Item=Box<Dog>>`
|
= help: the trait `FromIterator<Box<Dog>>` is not implemented for `Vec<Box<dyn Animal>>`
= help: the trait `FromIterator<T>` is implemented for `Vec<T>`
note: required by a bound in `collect`
For more information about this error, try `rustc --explain E0277`.
我也尝试插入
.map(Into::into)
以将Box<Dog>
转换为Box<dyn Animal>
,但是会出现错误the trait bound `Box<dyn Animal>: From<Box<Dog>>` is not satisfied
(未满足“Box<dyn Animal>: From<Box<Dog>>”的特质限定)。那么我应该如何将我的Box<Dog>
集合成Box<dyn Animal>
呢?
Box::<dyn T>::new(v)
。 - ImajinDevonas
关键字。 - Chayim Friedman.map(|v| -> Box<dyn Animal> { Box::new(v) })
,但是as _
更好。 - A. KriegmanBox<Dog>
强制转换为Box<dyn Animal>
不是一个无操作,因此有时我们必须要有点显式。 - A. Kriegman