1

I'm trying to implement a generic gcd function, but I can't figure out how to force a % b to have a specific type. What I have is this:

use std::ops::{Div,Rem};
use std::cmp::Eq;
use std::num::Zero;

fn gcd<T: Rem + Eq + Zero>(a: T, b: T) -> T {
    if b == T::zero() { a } 
    else { gcd(b, a % b) }
}

This fails because a % b has type T::Output, not T.

I tried:

// This doesn't even make sense, since Output is a member of T
fn gcd<T: Rem + Eq + Zero, Output = T>(a: T, b: T) -> T { 

// Syntax Error
fn gcd<T: Rem + Eq + Zero, T::Output = T>(a: T, b: T) -> T {

// Equality constraints not supported in where clauses.
fn gcd<T: Rem + Eq + Zero>(a: T, b: T) -> T 
    where T::Output = T {

How can I do this, and is there a better way?

zstewart
  • 2,093
  • 12
  • 24

0 Answers0