I am trying to give a static method reference and type argument for Box::new
and could not manage to compile it.
I have the following structure:
trait MyTrait {
fn hello(&self);
}
struct MyStruct;
impl MyTrait for MyStruct {
fn hello(&self) {
println!("Hello");
}
}
In my main method, I want to cast these structs to trait objects, put them in a Box
, and return it as a vector. I have managed to do it this way:
fn main() {
let my_vec = vec![MyStruct];
let my_trait_vec: Vec<Box<MyTrait>> = my_vec
.into_iter()
.map(|x| {
let boxed: Box<MyTrait> = Box::new(x);
boxed
})
.collect();
}
I am looking for something like :
let mut my_trait_vec: Vec<Box<MyTrait>> = my_vec.into_iter().map(Box::new::<MyTrait>).collect();
This is not accepted by the compiler and it complains about an unexpected type argument for Box::new()
.
Is it possible to make this boxing operation in a single line without declaring any external function?