We can use std::any::Any
to gather different types into a Box
.
use std::any::Any;
fn foo(value: Box<dyn Any>) {
if let Some(string) = value.downcast_ref::<String>() {
println!("String: {}", *string);
} else if let Some(int) = value.downcast_ref::<i32>() {
println!("i32: {}", *int);
}
}
fn main() {
let x = Box::new("hello".to_owned());
let y = Box::new(123);
foo(x);
foo(y);
}
we can also use downcast
to identify the type of a value in a Box
. I learnt that the types in C++ can be determined by virtual functions, according to this question, How does RTTI work?. However, types like i32
can also be downcasted in Rust. How does it work?