【发布时间】:2022-12-11 20:19:08
【问题描述】:
在铁锈中:
let int: i32 = 3;
let float: f32 = 3.3;
let res = int*float; // Invalid
let res = (int as f32)*float; // Valid
为了使这更容易,我希望在 * 运算符上实现覆盖,鉴于 Rust 的错误消息,这似乎是可能的:
cannot multiply `{integer}` by `{float}`
the trait `Mul<{float}>` is not implemented for `{integer}`
the following other types implement trait `Mul<Rhs>`:
但是写 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
那么应该怎么做呢?是否有板条箱已经实施了这些?
【问题讨论】:
-
编译器根本不允许这样做。
-
您不能为您不拥有的类型实现您不拥有的特征。
标签: rust