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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With