How to get a reference to a concrete type from a trait object?
How do I get Box<B>
or &B
or &Box<B>
from the a
variable in this code:
trait A {}
struct B;
impl A for B {}
fn main() {
let mut a: Box<dyn A> = Box::new(B);
let b = a as Box<B>;
}
This code returns an error:
error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>`
--> src/main.rs:8:13
|
8 | let b = a as Box<B>;
| ^^^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
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.
It should be clear that the cast can fail if there is another type C
implementing A
and you try to cast Box<C>
into a Box<B>
. I don't know your situation, but to me it looks a lot like you are bringing techniques from other languages, like Java, into Rust. I've never encountered this kind of Problem in Rust -- maybe your code design could be improved to avoid this kind of cast.
If you want, you can "cast" pretty much anything with mem::transmute
. Sadly, we will have a problem if we just want to cast Box<A>
to Box<B>
or &A
to &B
because a pointer to a trait
is a fat-pointer that actually consists of two pointers: One to the actual object, one to the vptr. If we're casting it to a struct
type, we can just ignore the vptr. Please remember that this solution is highly unsafe and pretty hacky -- I wouldn't use it in "real" code.
let (b, vptr): (Box<B>, *const ()) = unsafe { std::mem::transmute(a) };
EDIT: Screw that, it's even more unsafe than I thought. If you want to do it correctly this way you'd have to use std::raw::TraitObject
. This is still unstable though. I don't think that this is of any use to OP; don't use it!
There are better alternatives in this very similar question: How to match trait implementors