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?
Asked
Active
Viewed 7,759 times
1 Answers
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
-
1Thanks, 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