Clone an Rc trait object and cast it

后端 未结 1 1555
傲寒
傲寒 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>) -> 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

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