Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to a concrete type from a trait object?

Tags:

rust

traits

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 
like image 952
Aleksandr Avatar asked Nov 13 '15 07:11

Aleksandr


People also ask

What are trait objects?

A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of an object safe base trait plus any number of auto traits. Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.

Can trait be used for objects?

But trait objects differ from traditional objects in that we can't add data to a trait object. Trait objects aren't as generally useful as objects in other languages: their specific purpose is to allow abstraction across common behavior.

What is dyn rust?

dyn is a prefix of a trait object's type. The dyn keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be 'object safe'. Unlike generic parameters or impl Trait , the compiler does not know the concrete type that is being passed.

What are rust traits?

A trait in Rust is a group of methods that are defined for a particular type. Traits are an abstract definition of shared behavior amongst different types. So, in a way, traits are to Rust what interfaces are to Java or abstract classes are to C++. A trait method is able to access other methods within that trait.


2 Answers

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.

like image 96
DK. Avatar answered Sep 20 '22 06:09

DK.


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

like image 24
Lukas Kalbertodt Avatar answered Sep 19 '22 06:09

Lukas Kalbertodt