Rust Trait object conversion

后端 未结 2 1477
醉梦人生
醉梦人生 2020-12-11 19:02

The following code won\'t compile due to two instances of this error:

error[E0277]: the trait bound Self: std::marker::Sized is not satis

2条回答
  •  旧巷少年郎
    2020-12-11 19:29

    I found what I consider to be a great solution that didn't require new compiler features.

    pub trait Component {
        // ...
    }
    
    pub trait ComponentAny: Component + Any {
        fn as_any(&self) -> &Any;
        fn as_any_mut(&mut self) -> &mut Any;
    }
    
    impl ComponentAny for T
        where T: Component + Any
    {
        fn as_any(&self) -> &Any {
            self
        }
    
        fn as_any_mut(&mut self) -> &mut Any {
            self
        }
    }
    

    From here, I just change all my APIs to accept ComponentAny instead of Component. Because Any is automatically implemented for any 'static type, ComponentAny is now automatically implemented for any 'static type that implements Component. Thanks to Is there a way to combine multiple traits in order to define a new trait? for the idea.

提交回复
热议问题