Given an array of objects that implement a specific trait, I would like to iterate over them and run a function that takes a boxed trait, as follows:
use std::boxed::Box;
trait MyTrait {
fn go(&self);
}
struct MyStruct1 {}
struct MyStruct2 {}
impl MyTrait for MyStruct1 {
fn go(&self) {
println!("Go MyStruct1");
}
}
impl MyTrait for MyStruct2 {
fn go(&self) {
println!("Go MyStruct2");
}
}
fn go_boxed(t: Box<MyTrait>) {
t.go();
}
fn main() {
let t1 = MyStruct1 {};
let t2 = MyStruct2 {};
let ts: Vec<&MyTrait> = vec![&t1, &t2];
go_boxed(Box::from(t1));
go_boxed(Box::from(t2));
// This will fail:
ts.into_iter()
.for_each(|x| go_boxed(Box::new(x) as Box<MyTrait>));
}
Error:
error[E0277]: the trait bound `&dyn MyTrait: MyTrait` is not satisfied
--> src/main.rs:35:32
|
35 | .for_each(|x| go_boxed(Box::new(x) as Box<MyTrait>));
| ^^^^^^^^^^^ the trait `MyTrait` is not implemented for `&dyn MyTrait`
|
= note: required for the cast to the object type `dyn MyTrait`
What is happening? How can I work with vector of elements without knowing the concrete type of each element?
The referred question does not face my more trivial issue, which is why it is not compiling.