I would like to store any type in a Vec, and match against the actual type that is stored in the Vec.
Here is my attempt:
use std::any::Any;
fn main() {
let mut a = Vec::<Box<dyn Any>>::new();
a.push(Box::new(42));
a.push(Box::new("hello"));
a.push(Box::new(99));
for n in a {
let type_id = (&*n).type_id();
println!("{type_id:?}");
match n {
i32 => println!("i32"),
str => println!("str"),
_ => println!("unhandled type")
}
}
}
However this always prints "i32", and I get an unreachable pattern warning.
How do I match against Any?
You cannot match the type per se, but you can ask if it is of any specific type with
Any::is
:Playground