Is there a way other than traits to add methods to a type I don't own?

前端 未结 2 1840
半阙折子戏
半阙折子戏 2020-11-29 10:54

I\'m trying to extend the Grid struct from the piston-2dgraphics library. There\'s no method for getting the location on the window of a particular cell, so I implemented a

2条回答
  •  没有蜡笔的小新
    2020-11-29 11:29

    As of Rust 1.27, no, there is no other way. It's not possible to define inherent methods on a type defined in another crate.

    You can define your own trait with the methods you need, then implement that trait for an external type. This pattern is known as extension traits. The name of extension traits, by convention, ends with Ext, to indicate that this trait is not meant to be used as a generic bound or as a trait object. There are a few examples in the standard library.

    trait DoubleExt {
        fn double(&self) -> Self;
    }
    
    impl DoubleExt for i32 {
        fn double(&self) -> Self {
            *self * 2
        }
    }
    
    fn main() {
        let a = 42;
        println!("{}", 42.double());
    }
    

    Other libraries can also export extension traits (example: byteorder). However, as for any other trait, you need to bring the trait's methods in scope with use SomethingExt;.

提交回复
热议问题