Defining a trait for arithmetic operations on integers

I need a trait that allows almost all arithmetic operations on integers u8, u16, u32, u64, u128. Problem is that some operations like Rem need an output. So take this as an example:

use num_traits::PrimInt;

pub trait PrimUint: PrimInt {}
impl PrimUint for u8 {}
impl PrimUint for u16 {}
impl PrimUint for u32 {}
impl PrimUint for u64 {}
impl PrimUint for u128 {}

pub trait UnsignedMath: PrimUint + std::ops::Rem{}
impl<T: PrimUint> UnsignedMath for T{}

pub fn modulo<T: UnsignedMath, M: UnsignedMath>(t: T, m: M) -> T {
    t % m

here, I can't do $t%m$ because T and M are of different types. However, I think that all of the types that implement PrimUint can do Rem by themselves or the others.

So, what would be a good solution here? I didn't want T and M to be the same type, because I might want modulo to take the modulo of u64 by u8, for example.

It's not going to be possible to define a modulo that works between any two types that implement UnsignedMath.

You could use M: Into<T> and t % m.into().

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.