Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement commutative (scalar) multiplication with a built-in type like `f64`?

Tags:

rust

I'd like to implement a commutative scalar f64 multiplication operation using the * operator. Implementing the Mul<f64> trait for my type gives me a right side multiplication like.

struct Foo(f64);

impl Mul<f64> for Foo {
    type Output = Foo;

    fn mul(self, _rhs: f64) -> Foo {
        // implementation
    }
}

let a = Foo(1.23);
a * 3.45; // works
3.45 * a; // error: the trait bound `{float}: std::ops::Mul<Foo>` is not satisfied [E0277]

For a non-builtin scalar type, I can implement the same trait the other way round on the scalar, i.e. implementing Mul<Foo> on my scalar type.

How do I get a left side implementation for a built-in type like f64 too?

like image 581
fkjogu Avatar asked Aug 08 '16 13:08

fkjogu


1 Answers

You can simply reverse your implementation, by swapping f64 with Foo

impl std::ops::Mul<Foo> for f64 {
    type Output = Foo;

    fn mul(self, rhs: Foo) -> Foo {
        rhs * self
    }
}

Try it out in the Playground

like image 80
oli_obk Avatar answered Sep 22 '22 06:09

oli_obk