How to Use the Any Trait for Runtime Type Checking

Use the Any trait and downcast_ref method to check a value's concrete type at runtime in Rust.

Use the Any trait with downcast_ref to check a value's concrete type at runtime when stored as a trait object. This requires the concrete type to implement Any (which most do by default) and the trait object to be dyn Any + Send + Sync or similar.

use std::any::Any;

trait MyTrait {
    fn as_any(&self) -> &dyn Any;
}

struct Foo;
impl MyTrait for Foo {
    fn as_any(&self) -> &dyn Any { self }
}

fn check_type(obj: &dyn MyTrait) {
    if let Some(foo) = obj.as_any().downcast_ref::<Foo>() {
        println!("It is a Foo!");
    }
}