Clone an Rc trait object and cast it

后端 未结 1 1581
傲寒
傲寒 2021-01-07 07:10

This question is related to Rust: Clone and Cast Rc pointer

Let\'s say I have this piece of code which works fine:



        
相关标签:
1条回答
  • 2021-01-07 07:37

    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<RefCell<Self>>) -> Rc<RefCell<dyn TraitA>>;
        fn as_b(it: Rc<RefCell<Self>>) -> Rc<RefCell<dyn TraitB>>;
    }
    

    The trait can then be implemented as

    impl TraitAB for MyType {
        fn as_a(it: Rc<RefCell<MyType>>) -> Rc<RefCell<dyn TraitA>> {it}
        fn as_b(it: Rc<RefCell<MyType>>) -> Rc<RefCell<dyn TraitB>> {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<T: TraitA + TraitB + 'static> TraitAB for T {
        fn as_a(it: Rc<RefCell<T>>) -> Rc<RefCell<dyn TraitA>> {it}
        fn as_b(it: Rc<RefCell<T>>) -> Rc<RefCell<dyn TraitB>> {it}
    }
    

    Note that T: 'static because the trait objects in the function return types have an implicit 'static lifetime bound.

    Playground

    0 讨论(0)
提交回复
热议问题