在铁锈中:
let int: i32 = 3;
let float: f32 = 3.3;
let res = int*float; // Invalid
let res = (int as f32)*float; // Valid
Run Code Online (Sandbox Code Playgroud)
为了使这更容易,我希望在*运算符上实现覆盖,考虑到 Rust 的错误消息,这似乎是可能的:
cannot multiply `{integer}` by `{float}`
the trait `Mul<{float}>` is not implemented for `{integer}`
the following other types implement trait `Mul<Rhs>`:
Run Code Online (Sandbox Code Playgroud)
但写作impl Mul<i32> for f32显然也是不可能的:
only traits defined in the current crate can be implemented for primitive types
define and implement a trait or new type instead
Run Code Online (Sandbox Code Playgroud)
那么应该怎么做呢?是否有一个箱子已经实现了这些?
您无法为原语实现 Mul。这是 rusts 外来类型规则的一部分:对于您的板条箱中的实现,您的板条箱中必须至少定义了一种实现的类型或特征。由于 Mul 和原语都没有在您的代码中定义,因此您无法为它们创建实现。
如果您确实想这样做,则需要围绕 f32 创建一个包装类型,并在其上实现 Mul 和所有其他相关运算符。