Sub topic 15
Recovering concrete types with dyn Any
This chapter assumes you know how Box<dyn Trait> works, what a supertrait is, and that dyn Trait hides the concrete type. Sometimes you need that type back, for example to read a field that is not part of the trait. std::any::Any lets you do that with a runtime check.
How Any works
Any is a trait implemented for every type that is 'static, meaning it holds no non-static borrows. Each type has a unique TypeId. A &dyn Any can compare its stored type against a type you name. If they match, you get a reference to the concrete value. If they don't, you get None.
The main methods are:
| Method | Works on | Result |
|---|---|---|
| `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>>` |
| `is::<T>()` | `&dyn Any` | `bool` |
Downcasting your own trait objects
A dyn Component is not a dyn Any, so you expose one through a method. Making Any a supertrait of Component guarantees every implementor is 'static, so the conversion is always possible.
use std::any::Any;
trait Component: Any {
fn as_any(&self) -> &dyn Any;
}
struct Health(u32);
struct Name(String);
impl Component for Health {
fn as_any(&self) -> &dyn Any {
self
}
}
impl Component for Name {
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let items: Vec<Box<dyn Component>> = vec![
Box::new(Health(10)),
Box::new(Name(String::from("orc"))),
];
for c in &items {
match c.as_any().downcast_ref::<Health>() {
Some(h) => println!("health = {}", h.0),
None => println!("not a Health"),
}
}
}This prints health = 10, then not a Health.
The body self looks identical in both impls, but it is not redundant. Inside each impl, self has a known concrete type, so &Self coerces to &dyn Any there. A default method in the trait cannot do this, because Self may not be sized.
In recent Rust versions (trait upcasting is stable since 1.86), you can skip as_any and write let a: &dyn Any = c.as_ref(); when Any is a supertrait. On older compilers you need the method.
Downcasting a Box<dyn Any>
When you own the box, downcast moves the value out on success and hands the box back on failure, so you can try another type.
use std::any::Any;
fn main() {
let v: Box<dyn Any> = Box::new(42i32);
match v.downcast::<String>() {
Ok(s) => println!("string {}", s),
Err(v) => match v.downcast::<i32>() {
Ok(n) => println!("i32 {}", n),
Err(_) => println!("unknown"),
},
}
}This prints i32 42.
Common errors
- A borrowed type fails to compile.
Anyrequires'static. A struct holding&'a strcannot be put behinddyn Any. - You downcast the wrong value.
Box<dyn Component>is itself'static, so it also implementsAny. If you write(&boxed as &dyn Any), you get adyn Anywhose type isBox<dyn Component>, and every downcast to your own type returnsNone. Callas_any()on the inner value instead. - Mutation has no path.
as_anygives only shared access. Addfn as_any_mut(&mut self) -> &mut dyn Anyand usedowncast_mut.
Exercise
A function takes items: &[Box<dyn Component>] and calls item.as_any().downcast_ref::<Name>() on each one. What does it return for a Health item, and why does the trait need Any as a supertrait?
Show answer
It returns None, because the stored TypeId is Health, not Name. The Any supertrait guarantees every implementor is 'static, which as_any needs to return &dyn Any.