satylogin's blog

By satylogin, history, 7 weeks ago, In English

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
    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() {
    } else {
        gcd(b, a % b)

I am uploading such generic things in my repo as and when I need something:

  • Vote: I like it
  • +18
  • Vote: I do not like it