By satylogin, history, 7 weeks ago,

I was trying to come up with a generic implementation of gcd in rust that I could use by copy pasting without worrying about data type. I finally have something useful that works on sane data types.

I am sharing the implementation in case someone needs it

/// Calculates gcd for same types T that implements required traits.
/// The current implementation is tested on i32, u32, i64, u64, usize, isize
/// For any other type T, the behaviour is undefined
pub fn gcd<T>(a: T, b: T) -> T
where
T: std::cmp::PartialEq + std::ops::Rem<Output = T> + Default + Copy,
{
// for our required types, default evalutaes to 0 at compile time.
// and thus have 0 cost abstraction.
if b == T::default() {
a
} else {
gcd(b, a % b)
}
}