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?
Finn
2
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
Finn
3
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 @RustyYato solved it at Converting Rc<Trait> types - #2 by RustyYato -- 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 @RustyYato 's full solution.
1 Like
There's actually a long running PR implementing this: https://github.com/rust-lang/rust/pull/60900
system
Closed
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.