Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I constrain T in Rust to accept only numeric types? [duplicate]

Tags:

generics

rust

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?

like image 315
Midas Avatar asked Sep 03 '17 08:09

Midas


1 Answers

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);
like image 124
Lukazoid Avatar answered Nov 17 '22 00:11

Lukazoid