Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Core Traits

The Any trait

Reference for Rust std::any::Any: runtime type identification with TypeId, downcast_ref, downcast_mut, Box<dyn Any> downcast, the 'static requirement and limits.

std::any::Any lets you ask, at run time, what concrete type sits behind a trait object. It is implemented automatically for every type that has no non-'static references. With a &dyn Any or Box<dyn Any> you can test the real type with is::<T>() and recover a typed reference with downcast_ref::<T>() or downcast_mut::<T>().

Rust is statically typed, so Any is a deliberate escape hatch for plugin systems, heterogeneous maps, event buses and panic payloads. Where possible prefer enums or generics, which the compiler can check.

Rust
let x: &dyn Any = &5_i32;
assert!(x.is::<i32>());

Try it

Rust Downcasting a dyn Any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust A type-keyed registry with TypeId

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub trait Any: 'static {
    fn type_id(&self) -> TypeId;
}

impl dyn Any {
    pub fn is<T: Any>(&self) -> bool;
    pub fn downcast_ref<T: Any>(&self) -> Option<&T>;
    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T>;
}

impl Box<dyn Any> {
    pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>>;
}

pub fn type_name<T: ?Sized>() -> &'static str;
TypeId::of::<T>()
Item Description
TypeId::of::<T>() A value that identifies a type; comparable and hashable. Requires T: 'static.
is::<T>() true when the hidden type is exactly T.
downcast_ref / downcast_mut Some reference when the type matches, otherwise None.
Box::downcast Returns Ok(Box<T>) or gives the original box back in Err.
type_name::<T>() A readable name for debugging.

Errors / panics / edge cases: a failed downcast never panics; it returns None or Err. The text from type_name is not guaranteed to be stable and must not be used as a key.

Usage notes

  • 'static only. Types that borrow non-static data (&'a str with a short 'a) do not implement Any. &'static str does.
  • Exact types. Downcasting to &str does not find a String, and downcasting to a trait does not work at all; you can only downcast to concrete types.
  • Upcasting is limited. To get an &dyn Any from your own trait object, add a method fn as_any(&self) -> &dyn Any { self } to the trait (see dyn). Newer compilers allow trait upcasting coercion when Any is a supertrait.
  • Thread and error use. Box<dyn Any + Send> is the payload type of thread::JoinHandle::join errors and panic::catch_unwind; downcast to &str or String to read a panic message.
  • Cost. type_id is a virtual call and a comparison. It is cheap but not free; hot paths are better served by enums.
  • Not reflection. Any cannot list fields or call methods; it only identifies and recovers the type.
  • Alternatives. An enum for a closed set of types, generics for open sets known at compile time, and trait objects with real methods for behavior.