[英]Rust: can't collect an `Iterator<Item = Box<Dog>>` into `Vec<Box<dyn Animal>>`
我觉得这段代码应该可以工作,因为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>
s 转换为Box<dyn Animal>
s,但这会给错误the trait bound `Box<dyn Animal>: From<Box<Dog>>` is not satisfied
。
那么我应该如何将我的Box<Dog>
收集到Box<dyn Animal>
中?
您快到了。 问题是Box::new()
接受T
并给出Box<T>
。 强制是不可能的。
相反,您应该提供一个闭包|v| Box::new(v)
|v| Box::new(v)
,但即使这样还不够,因为编译器并没有立即意识到它需要强制,当它意识到时为时已晚(你可以在这里阅读更多内容)。 你需要暗示它。 一个简单as
就足够了: |v| Box::new(v) as _
|v| Box::new(v) as _
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.