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

I would like to implement a commutative scalar multiplication operation f64using an operator *. Implementing a trait Mul<f64>for my type gives me the correct multiplication, for example.

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 scalar type that is not built-in, you can implement the same attribute on the contrary in a scalar, i.e. implementing Mul<Foo>on my scalar type.

How to get left implementation for inline type, for example f64?

+4
source share
1 answer

You can simply cancel your implementation by replacing f64withFoo

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

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

Try on the playground

+7
source

Source: https://habr.com/ru/post/1650550/


All Articles