Automatically display Add, Mul, Ord, etc. For numeric type

What's the easiest way to create a custom type that behaves like a number?

I want type checking to prevent mixing different modules in my program, but I still want to be able to easily do type calculations without quotes back and forth (similar case for custom types Centimeters

and Inches

) ..

If I create:

struct Centimeters(f64);

      

then I have to realize Add

, Mul

, Ord

and many other attributes manually. That a lot of templates and copying and pasting this code creates the risk of breaking basic arithmetic in the program :)

Unfortunately, #[derive(Add, Sub, …)]

it doesn't seem to be supported. Is there another standard trait / type / box that could achieve a similar effect?

+3


source to share


1 answer


This answer contains a nice macro to help you implement the traits of your new types.

There are now several boxes that make this very easy: custom_derive and newtype_derive .
They let you do

custom_derive! {
  #[derive(NewtypeAdd, NewtypeMul)]
  pub struct Centimeters(i32);
}

      



implement Add

and Mul

for your new type.

You should take a look at https://crates.io/crates/units . This box may already allow you to do what you want.

Alternatively https://crates.io/crates/measurements might be a good solution.

+5


source







All Articles