3

I have a situation similar to the following:

use std::rc::Rc;
trait A {}
trait B: A {}
struct Impl {}

impl A for Impl {}
impl B for Impl {}

I would like to be able to cast trait objects of these traits like in the following:

fn main() {
    let val: Rc<Box<A>> = Rc::new(Box::new(Impl {}));
    let test: Rc<Box<B>> = val as Rc<Box<B>>;
}

This gives me a compiler-error that this is a non-scalar cast. I guess I am doing the wrong sort of cast, but I do not see how this is supported. Further, I would like the cast to be safe, i.e. returning me an Option<Rc<Box<B>>. Is this possible or is the dynamic dispatch implemented such that trait objects cannot be converted between traits?

Edit: I forgot to say, I am using the nightly version, in case this should matter.

Georg
  • 5,626
  • 1
  • 23
  • 44
  • @Shepmaster Thanks for pointing out my mistake to forget the braces when creating a new object. I do not get the error regarding the trait bound that `A` should be `Sized`, though. – Georg Mar 02 '17 at 22:23
  • 3
    Perhaps a duplicate of [Why doesn't Rust support trait object upcasting?](http://stackoverflow.com/q/28632968/155423), or [Downcast traits inside Rc for AST manipulation](http://stackoverflow.com/q/40024093/155423). Note that the term you are probably searching for is "downcast" or "upcast", depending on direction. – Shepmaster Mar 02 '17 at 22:25
  • FWIW, `struct Impl;` allows for `let a = Impl`. The lack of braces on the definition has meaning. – Shepmaster Mar 02 '17 at 22:26

0 Answers0