More 'lowering' Rc <dyn Trait> problems

I acknowledge this is likely a corollary to some question I've already asked. I can't figure out how to make this compile:

use std::rc::Rc;

pub trait A {}
pub trait B: A {}

fn goal(x: Rc<dyn B>) -> Rc<dyn A> {
    x
}

How do I make this compile? If something satisfies B, it clearly satisfies A, so why can't we do this conversion?

This seems to be a desirable feature and has indeed been discussed before, see:

For more material, search for "trait upcast" in a search machine.

1 Like

In the meantime, self: Rc<Self> has been stabilized, so we can apply the scheme:

trait A {}

trait IntoA {
    fn rc_into_a(self: Rc<Self>) -> Rc<dyn A>;
}

trait B: A+IntoA {}

impl<T: B+'static> IntoA for T {
    fn rc_into_a(self: Rc<Self>) -> Rc<dyn A> { self }
}

fn goal(x: Rc<dyn B>) -> Rc<dyn A> {
    x.rc_into_a()
}
1 Like

Turns out I posted a "larger" problem and @KrishnaSannasi solved it at Converting Rc<Trait> types -- but I did not fully understand the solution last time.

@Finn : Thanks for posting your solution. It "refactors out" and makes it easier for me to understand part of @KrishnaSannasi 's full solution.

1 Like

There's actually a long running PR implementing this: https://github.com/rust-lang/rust/pull/60900