[rust-dev] std::num::pow() is inadequate / language concepts

Patrick Walton pcwalton at mozilla.com
Fri Jul 25 10:30:56 PDT 2014

On 7/25/14 10:11 AM, Oscar Boykin wrote:
> Did I miss a point in this thread where using a typeclass/trait to
> implement exponentiation was dismissed?
> This function could be changed to:
> fn pow<T: HasPow>(base: T, exp: uint) -> T { base.pow(exp) }
> trait HasPow {
>    fn pow(self: Self, exp: uint) -> Self
> }
> Or, just use HasPow in your code.
> Why is this not a solution?

Yes, I was about to bring this up. You might want to conceivably have 
different types for the parameters, which Associated Types would solve 
nicely. For the maximum genericity:

     trait Pow {
         type This;
         type Exp;
         type Result;
         fn pow(this: This, exp: Exp) -> Result;

You can then write functions that take Powable things:

     fn whatever<P:Pow>(p: P) -> P {
         p.pow(p, 1)

Now the only restriction that is left is that all instances of `Pow` 
must have the same number of arguments. Presumably this is not too 
onerous. :)


More information about the Rust-dev mailing list