In the standard library, the std::any::Any trait comes with downcast methods which let you cast from an Any trait object to a concrete type.

let x : i32 = 7 ; let y : & dyn Any = & x ; assert_eq ! ( y . downcast_ref :: < i32 > (), Some ( & 7 )); assert_eq ! ( y . downcast_ref :: < f32 > (), None );

However, it is not possible to downcast to a trait object.

ⓘ This example deliberately fails to compile

use std :: any :: Any ; trait Foo { fn foo ( & self ) -> i32 ; } struct A { x : i32 } impl Foo for A { fn foo ( & self ) -> i32 { self . x } } let x = A { x : 7 }; let y : & dyn Any = & x ; let z : Option < & dyn Foo > = y . downcast_ref ();

This library provides a way of casting from dyn Any to trait objects.