2

In Rust :

let int: i32 = 3;
let float: f32 = 3.3;
let res = int*float; // Invalid
let res = (int as f32)*float; // Valid

To make this easier, I'm looking to implement an override on the * operator, which seems to be possible given Rust's error message :

cannot multiply `{integer}` by `{float}`
the trait `Mul<{float}>` is not implemented for `{integer}`
the following other types implement trait `Mul<Rhs>`:

But writing impl Mul<i32> for f32 is apparently not possible either :

only traits defined in the current crate can be implemented for primitive types
define and implement a trait or new type instead

So how is that supposed to be done ? Is there a crate already implementing those ?

oui
  • 89
  • 4

1 Answers1

5

You can't implement Mul for a primitive. This is part of rusts foreign type rules: For an implementation in your crate, at least one of the implemented type or trait must have been defined in your crate. Since neither Mul nor the primitive are defined in your code, you can't create an implementation for them.

If you really want to do this, you need to create a wrapper type around f32, and implement Mul and all the other relevant operators on that.

user1937198
  • 4,987
  • 4
  • 20
  • 31