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.
let x: &dyn Any = &5_i32; assert!(x.is::<i32>());
Try it
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.
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
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
'staticonly. Types that borrow non-static data (&'a strwith a short'a) do not implementAny.&'static strdoes.- Exact types. Downcasting to
&strdoes not find aString, and downcasting to a trait does not work at all; you can only downcast to concrete types. - Upcasting is limited. To get an
&dyn Anyfrom your own trait object, add a methodfn as_any(&self) -> &dyn Any { self }to the trait (seedyn). Newer compilers allow trait upcasting coercion whenAnyis a supertrait. - Thread and error use.
Box<dyn Any + Send>is the payload type ofthread::JoinHandle::joinerrors andpanic::catch_unwind; downcast to&strorStringto read a panic message. - Cost.
type_idis a virtual call and a comparison. It is cheap but not free; hot paths are better served by enums. - Not reflection.
Anycannot list fields or call methods; it only identifies and recovers the type. - Alternatives. An
enumfor a closed set of types, generics for open sets known at compile time, and trait objects with real methods for behavior.
Related
dyn,std::error::Error,Sized,SendandSync- Lessons: Trait objects, Panic, Type system tricks