I'm taking an iterator of some type that must implement the trait A
, and trying to convert it into a Vec
of Box
es of that trait:
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>>>()
}
However, this fails to compile, saying:
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
This error kind of makes sense, but then I don't see why there's no problem with the following:
fn test<'a, T: A + 'a>(t: T) -> Box<A + 'a> {
Box::new(t)
}
How is that any different? How can I express that I'd like to Box
them as A
s, rather than whatever type they may be?
You need to cast the
Box<I::Item>
into aBox<A>
:As Sven Marnach points out: