我正在采用某种类型的迭代器,必须实现特征A
,并尝试将其转换为Vec
的Box
es的特征:
trait A {}
fn test2<'a, I>(iterator: I) -> Vec<Box<A + 'a>>
where
I: IntoIterator,
I::Item: A + 'a,
{
iterator
.into_iter()
.map(|a| Box::new(a))
.collect::<Vec<Box<A + 'a>>>()
}
然而,这无法编译,说:
error[E0277]: the trait bound `std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not satisfied
--> src/main.rs:11:10
|
11 | .collect::<Vec<Box<A + 'a>>>()
| ^^^^^^^ a collection of type `std::vec::Vec<std::boxed::Box<A + 'a>>` cannot be built from an iterator over elements of type `std::boxed::Box<<I as std::iter::IntoIterator>::Item>`
|
= help: the trait `std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` is not implemented for `std::vec::Vec<std::boxed::Box<A + 'a>>`
= help: consider adding a `where std::vec::Vec<std::boxed::Box<A + 'a>>: std::iter::FromIterator<std::boxed::Box<<I as std::iter::IntoIterator>::Item>>` bound
这种错误是有道理的,但后来我不明白为什么以下没有问题:
fn test<'a, T: A + 'a>(t: T) -> Box<A + 'a> {
Box::new(t)
}
怎么会有什么不同?我怎么能表达我想将Box
作为A
s,而不是它们可能是什么类型?
你需要将Box<I::Item>
投射到Box<A>
:
fn test2<'a, I>(iterator: I) -> Vec<Box<dyn A + 'a>>
where
I: IntoIterator,
I::Item: A + 'a,
{
iterator
.into_iter()
.map(|a| Box::new(a) as Box<dyn A>)
.collect()
}
[直接返回
Box::new
]有何不同?
您不需要在函数中进行显式强制转换的原因是块的最后一个语句是强制站点,并且在这些站点上隐式发生强制。有关详细信息,请参阅the chapter on coercions in the nomicon。