This question is related to Rust: Clone and Cast Rc pointer
Let\'s say I have this piece of code which works fine:
You can work around this issue by not using a receiver in TraitAB
's casting methods (i.e. by declaring them as associated functions):
trait TraitAB : TraitA + TraitB {
fn as_a(it: Rc>) -> Rc>;
fn as_b(it: Rc>) -> Rc>;
}
The trait can then be implemented as
impl TraitAB for MyType {
fn as_a(it: Rc>) -> Rc> {it}
fn as_b(it: Rc>) -> Rc> {it}
}
These functions can then be called using the fully qualified syntax.
a = TraitAB::as_a(ab.clone());
b = TraitAB::as_b(ab.clone());
The TraitAB
implementation for all types will be the same. To make this implementation available for all types implementing TraitA
and TraitB
, you can use a generic impl
:
impl TraitAB for T {
fn as_a(it: Rc>) -> Rc> {it}
fn as_b(it: Rc>) -> Rc> {it}
}
Note that T: 'static
because the trait objects in the function return types have an implicit 'static
lifetime bound.
Playground