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

前端 未结 3 2078
生来不讨喜
生来不讨喜 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:06

    For Rust version 1.10.0, it seems to me that type aliases would perfectly fit the situation you are describing. They simply give a type a different name.

    Let's say all centimeters are u32s. Then I could just use the code

    type Centimeters = u32;
    

    Any trait that u32 has, Centimeters would automatically have. This doesn't eliminate the possibility of adding Centimeters to Inches. If you're careful, you wouldn't need different types.

提交回复
热议问题