6

I want to create some structs that have a property of a generic type T. This generic type will be used for calculations, so I want T to be all kind of numeric types such as i32, u32, f32, uf32, i64 etc. How can I achieve that?

Midas
  • 564
  • 6
  • 21
  • 1
    Why not depend on the traits you actually need, in addition to perhaps the `Copy` trait? That will cover numbers and number-like objects devised in the future (think complex numbers or with non-standard sizes). – user4815162342 Sep 03 '17 at 12:23

1 Answers1

11

This is what the num-traits crate can be used for. The Num trait is implemented for all numeric types.

This ensures your generic type T has all of the expected numeric operators, Add, Sub, Mul, Div, Rem, can be partially equality checked via PartialEq, it also exposes a value for 1 and 0 for T.

You can see how the crate implements the trait here:

int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64);
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
  • 1
    Thanks, that sounds promising. However, there must be a way in the Rust language itself to implement this right? In C# for example you have the where keyword that constrains the accepted types. The crate itself must have been using some language feature to do this. – Midas Sep 03 '17 at 09:12
  • 2
    @Midas They defined the trait `Num` and implemented it for all the standard numeric types. You could make your own trait `Num` and implement it for all numeric types, but you may as well use the crate. – Lukazoid Sep 03 '17 at 09:14
  • 5
    Just look at what the crate does, they're only cooking with water – the8472 Sep 03 '17 at 12:58