Automatically implement traits of enclosed type for Rust newtypes (tuple structs with one field)

前端 未结 3 2083
生来不讨喜
生来不讨喜 2020-11-30 07:54

In Rust, tuple structs with only one field can be created like the following:

struct Centimeters(i32);

I want to do basic arithmetic with <

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 08:14

    I made the derive_more crate for this problem. It can derive lots of traits for structs of which the elements implement them.

    You need to add derive_more to your Cargo.toml. Then you can write:

    #[macro_use]
    extern crate derive_more;
    
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Add)]
    struct Centimeters(i32);
    
    fn main() {
        let a = Centimeters(100);
        let b = Centimeters(200);
        assert_eq!(a + a, b);
    }
    

提交回复
热议问题