fkjogu
fkjogu

Reputation: 303

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

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?

Upvotes: 16

Views: 3727

Answers (1)

oli_obk
oli_obk

Reputation: 31283

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

Upvotes: 21

Related Questions