Sub topic 15
Recovering concrete types with dyn Any
A trait object hides the concrete type on purpose. Sometimes you need it back, for example to read a field that only one implementor has. dyn Any is the standard way to do this. This chapter covers how Any works, three ways to use it, and the mistakes that cause trouble.
This chapter assumes you know how Box<dyn Trait> and &dyn Trait work, what a supertrait is, and how Option and Result are matched. The earlier chapters on vtables and supertraits cover the rest.
What Any provides
std::any::Any is a trait with one method, type_id. It returns a TypeId, a value that identifies a concrete type at runtime. The standard library implements Any for every type that is 'static, meaning it contains no non-static borrowed references.
That blanket implementation makes dyn Any a trait object that every owned type can be coerced into. The impl dyn Any block adds the methods you use in practice:
| Method | Receiver | Result |
|---|---|---|
| `is::<T>()` | `&dyn Any` | `bool`, true if the concrete type is `T` |
| `downcast_ref::<T>()` | `&dyn Any` | `Option<&T>` |
| `downcast_mut::<T>()` | `&mut dyn Any` | `Option<&mut T>` |
| `downcast::<T>()` | `Box<dyn Any>` | `Result<Box<T>, Box<dyn Any>>` |
Each method compares the stored TypeId with TypeId::of::<T>(). If they match, it reinterprets the data pointer as &T or Box<T>. If not, it returns None or Err. There is no unsafe code in your program, and a wrong guess can't corrupt memory.
Downcasting from your own trait
You usually don't hold a dyn Any directly. You hold a Box<dyn Component> and want to ask whether it is a Health. A dyn Component is not a dyn Any, so you need a bridge. The standard pattern makes Any a supertrait and adds an as_any method that returns self as &dyn Any.
use std::any::Any;
trait Component: Any {
fn as_any(&self) -> &dyn Any;
fn as_any_mut(&mut self) -> &mut dyn Any;
}
struct Health(u32);
struct Name(String);
impl Component for Health {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
impl Component for Name {
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
fn main() {
let mut parts: Vec<Box<dyn Component>> = vec![
Box::new(Health(10)),
Box::new(Name(String::from("orc"))),
];
for p in parts.iter_mut() {
if let Some(h) = p.as_any_mut().downcast_mut::<Health>() {
h.0 += 5;
}
}
for p in &parts {
if let Some(h) = p.as_any().downcast_ref::<Health>() {
println!("health = {}", h.0);
} else if let Some(n) = p.as_any().downcast_ref::<Name>() {
println!("name = {}", n.0);
}
}
}This prints health = 15 and then name = orc.
The body of as_any is just self. Inside impl Component for Health, self is a &Health, and the return type asks for &dyn Any. The compiler applies an unsizing coercion, and the vtable it attaches is the Any vtable for Health. That vtable's type_id entry returns TypeId::of::<Health>().
You must write as_any in every implementor, because only a concrete type knows its own Self. A default method body can't do this, since Self may be unsized there and the coercion would not compile.
Why Any is a supertrait here
The : Any bound on Component is what limits implementors to 'static types. Without it, self could not be coerced to &dyn Any inside the impl. The bound also makes every implementor's Any impl reachable from the dyn Component vtable, which is what the next section uses.
Owned downcasts with Box<dyn Any>
If you own the value, Box<dyn Any> gives you downcast. On failure it returns the original box in the Err variant, so you can try another type without losing the value.
use std::any::Any;
fn describe(value: Box<dyn Any>) -> String {
match value.downcast::<String>() {
Ok(s) => format!("string: {s}"),
Err(value) => match value.downcast::<i32>() {
Ok(n) => format!("i32: {n}"),
Err(_) => String::from("unknown"),
},
}
}
fn main() {
println!("{}", describe(Box::new(String::from("hi"))));
println!("{}", describe(Box::new(7_i32)));
println!("{}", describe(Box::new(1.5_f64)));
}The output is string: hi, i32: 7, then unknown. Note that a successful downcast::<String>() gives you a Box<String>, and format! prints it through Display on the box's contents.
This style fits places where values of unrelated types pass through a generic layer, such as a plugin registry, a type-keyed map, or the payload of a caught panic. The payload from std::panic::catch_unwind is a Box<dyn Any + Send>, and callers typically try downcast_ref::<&str>() and downcast_ref::<String>() on it.
Upcasting to dyn Any
Since Rust 1.86, trait upcasting is stable. A dyn Component can be coerced directly to dyn Any when Any is a supertrait of Component. The as_any bridge is no longer needed on a toolchain at that version or newer.
use std::any::Any;
trait Component: Any {
fn name(&self) -> &'static str;
}
struct Health(u32);
impl Component for Health {
fn name(&self) -> &'static str {
"health"
}
}
fn main() {
let c: Box<dyn Component> = Box::new(Health(10));
println!("{}", c.name());
let any: Box<dyn Any> = c;
match any.downcast::<Health>() {
Ok(h) => println!("health = {}", h.0),
Err(_) => println!("not a Health"),
}
}This prints health and then health = 10. The coercion works because the dyn Component vtable contains a pointer to the supertrait's vtable, which the compiler can substitute.
Check your project's minimum supported Rust version before relying on this. On older compilers the line let any: Box<dyn Any> = c; fails with a type mismatch, and the as_any pattern is still the way to do it.
Gotchas
Calling type_id on the box
Box<dyn Any> is itself a 'static type, so it implements Any too. Calling .type_id() on the box can resolve to the box's own impl instead of the contents'.
use std::any::{Any, TypeId};
fn main() {
let b: Box<dyn Any> = Box::new(5_i32);
println!("{}", (*b).type_id() == TypeId::of::<i32>());
println!("{}", b.type_id() == TypeId::of::<i32>());
}The first line prints true. The second prints false, because b.type_id() returned the TypeId of Box<dyn Any>. Dereference first, or use is::<T>() and downcast_ref, which are defined on dyn Any and avoid the problem.
The same thing happens with a blanket impl<T: Any> Component for T. Then Box<dyn Component> also implements Component, and as_any called on the box returns the box, not the value inside. Prefer explicit impls per type, or call the method through &**boxed.
The 'static requirement
A type that holds a non-static reference, such as struct View<'a>(&'a str), does not implement Any. You can't put it in a dyn Any, and you can't make it a Component if Any is a supertrait. If your component types need borrowed data, Any is the wrong tool. Own the data (String, Arc<str>) or find a design that avoids downcasting.
Auto traits are part of the type
dyn Any, dyn Any + Send, and dyn Any + Send + Sync are three different types. Each has its own downcast_ref and downcast methods. A Box<dyn Any + Send> can't be passed where Box<dyn Any> is expected without a coercion, and the reverse direction is not allowed. If a value must cross threads, put Send in the type from the start.
When not to downcast
Downcasting breaks the abstraction a trait object provides. Each downcast_ref call is a runtime check that the compiler can't verify, and the chain of if let branches grows as you add types. Adding a new implementor doesn't produce a compile error at the places that should handle it.
Consider these alternatives first:
- Add a method to the trait. If callers need the health value,
fn health(&self) -> Option<u32>keeps the check in the trait. - Use an
enumwhen the set of types is closed. The compiler then enforces exhaustivematcharms. - Use generics when the concrete type is known at compile time.
Downcasting is a good fit when the set of types is open, when a framework stores values it can't name (an ECS component store, an event bus, a typed extension map), and when the caller knows which type it asked for.
Exercises
Exercise
A function takes b: Box<dyn Any> and runs b.type_id() == TypeId::of::<u8>() when b contains a u8. Why does the comparison give false, and what are two ways to fix it?
Show answer
Method resolution picks the Any impl for Box<dyn Any> itself, so type_id returns the TypeId of the box type, not of the u8 inside. Fix it by dereferencing first, (*b).type_id(), or by using b.is::<u8>() or b.downcast_ref::<u8>(), which are defined on dyn Any and look at the contents.
Exercise
Given trait Shape: Any { fn area(&self) -> f64; } and a Vec<Box<dyn Shape>>, write a function count_circles(shapes: &[Box<dyn Shape>]) -> usize for a Circle struct. State what you must add to Shape if your compiler is older than Rust 1.86.
Show answer
With Rust 1.86 or newer: shapes.iter().filter(|s| { let a: &dyn Any = &***s; a.is::<Circle>() }).count(). The expression &***s goes from &&Box<dyn Shape> through the box to dyn Shape, and the reference is upcast to &dyn Any. On an older compiler, add fn as_any(&self) -> &dyn Any; to Shape, implement it as self in every implementor, and call s.as_any().is::<Circle>().
Exercise
Why does struct View<'a>(&'a str); fail to work with Box<dyn Any>, and what is the practical fix?
Show answer
Any is only implemented for 'static types, and View<'a> borrows data with a shorter lifetime. Make the struct own its data, for example struct View(String);, or use a design that does not need runtime type recovery.