How do I require that a struct implements a generic trait?

As an example, say I have

trait CanMultiply<T>{
    fn multiply(op1: &T, op2: &T) -> T; 
}

struct Foo{
  // ...
}
impl CanMultiply<u64> for Foo{
 //... 
}

Then, I wish to write a "square" function. I want to do this using multiply. But how do I enforce that the Foo struct implements CanMultiply?

impl<T> Foo{ // some where clause? 
    fn square(op1: &T) -> T {
         Self::multiply(op1, op1)
    }
}

The goal of this is later if I add CanMultiply to the Foo implementation, I can automatically get the square function.

Since Foo isn't generic, you can't put the <T> on the impl block. There's nowhere left for it to go but on the function:

impl Foo {
    fn square<T>(op: &T) -> T where Self: CanMultiply<T> {
        Self::multiply(op, op)
    }
}
2 Likes