There are two ways to do downcasting in Rust. The first is to use Any
. Note that this only allows you to downcast to the exact, original concrete type. Like so:
use std::any::Any;
trait A {
fn as_any(&self) -> &dyn Any;
}
struct B;
impl A for B {
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let a: Box<dyn A> = Box::new(B);
// The indirection through `as_any` is because using `downcast_ref`
// on `Box<A>` *directly* only lets us downcast back to `&A` again.
// The method ensures we get an `Any` vtable that lets us downcast
// back to the original, concrete type.
let b: &B = match a.as_any().downcast_ref::<B>() {
Some(b) => b,
None => panic!("&a isn't a B!"),
};
}
The other way is to implement a method for each "target" on the base trait (in this case, A
), and implement the casts for each desired target type.
Wait, why do we need as_any
?
Even if you add Any
as a requirement for A
, it's still not going to work correctly. The first problem is that the A
in Box<dyn A>
will also implement Any
... meaning that when you call downcast_ref
, you'll actually be calling it on the object type A
. Any
can only downcast to the type it was invoked on, which in this case is A
, so you'll only be able to cast back down to &dyn A
which you already had.
But there's an implementation of Any
for the underlying type in there somewhere, right? Well, yes, but you can't get at it. Rust doesn't allow you to "cross cast" from &dyn A
to &dyn Any
.
That is what as_any
is for; because it's something only implemented on our "concrete" types, the compiler doesn't get confused as to which one it's supposed to invoke. Calling it on an &dyn A
causes it to dynamically dispatch to the concrete implementation (again, in this case, B::as_any
), which returns an &dyn Any
using the implementation of Any
for B
, which is what we want.
Note that you can side-step this whole problem by just not using A
at all. Specifically, the following will also work:
fn main() {
let a: Box<dyn Any> = Box::new(B);
let _: &B = match a.downcast_ref::<B>() {
Some(b) => b,
None => panic!("&a isn't a B!")
};
}
However, this precludes you from having any other methods; all you can do here is downcast to a concrete type.
As a final note of potential interest, the mopa crate allows you to combine the functionality of Any
with a trait of your own.