How do I implement a trait I don't own for a type I don't own?

后端 未结 2 930
忘掉有多难
忘掉有多难 2020-11-22 00:55

I wanted to implement the Shl trait for Vec, the code is below. This would make things like vec << 4 possible, which would be ni

2条回答
  •  既然无缘
    2020-11-22 01:43

    While you can't do that exactly, the usual workaround is to just wrap the type you want in your own type and implement the trait on that.

    use somecrate::FooType;
    use somecrate::BarTrait;
    
    struct MyType(FooType);
    
    impl BarTrait for MyType {
        fn bar(&self) {
            // use `self.0` here
        }
    }
    

提交回复
热议问题