use std::any::Any;
use std::any::TypeId;
trait Task {}
struct SomeTask;
impl Task for SomeTask {}
fn main() {
let tasks_a: Vec<Box<SomeTask>> = vec![Box::new(SomeTask)];
let tasks_b: Vec<Box<dyn Any>> = vec![Box::new(SomeTask)];
let tasks_c: Vec<Box<dyn Task>> = vec![Box::new(SomeTask)];
println!(
"Item stored in `Vec<Box<SomeTask>>` is of type `SomeTask`? {}",
TypeId::of::<SomeTask>() == (&*tasks_a[0]).type_id(),
);
println!(
"Item stored in `Vec<Box<dyn Any>>` is of type `SomeTask`? {}",
TypeId::of::<SomeTask>() == (&*tasks_b[0]).type_id(),
);
println!(
"Item stored in `Vec<Box<dyn Task>>` cast as `&dyn Any` is of type `SomeTask`? {}",
TypeId::of::<SomeTask>() == (&tasks_c[0] as &dyn Any).type_id(),
);
println!(
"Item stored in `Vec<Box<dyn Task>>` is of type `SomeTask`? {}",
TypeId::of::<SomeTask>() == (&*tasks_c[0]).type_id(),
);
}
Output:
Item stored in `Vec<Box<SomeTask>>` is of type `SomeTask`? true
Item stored in `Vec<Box<dyn Any>>` is of type `SomeTask`? true
Item stored in `Vec<Box<dyn Task>>` cast as `&dyn Any` is of type `SomeTask`? false
Item stored in `Vec<Box<dyn Task>>` is of type `SomeTask`? false
Can you help shed some light on the output? Specifically, I don't understand why item of T stored in Vec<Box<dyn Any>> is of type T, but that's not true for item stored in Vec<Box<dyn Trait>>.