gpt4 book ai didi

rust - 如何为自定义结构类型实现 Mul Trait 以两种方式工作

转载 作者:行者123 更新时间:2023-12-05 03:34:08 36 4
gpt4 key购买 nike

// main.rs
#[derive(Clone, Copy)]
struct A(f64, f64);
impl<T> Mul<T> for A
where
f64: From<T>,
T: Copy, // f64: Mul<T>,
{
type Output = A;
fn mul(mut self, rhs: T) -> Self::Output {
self.0 = self.0 * f64::from(rhs);
self.1 = self.1 * f64::from(rhs);
self
}
}

impl Mul<A> for i32 {
type Output = A;
fn mul(self, mut rhs: A) -> Self::Output {
rhs.0 = rhs.0 * f64::from(self);
rhs.1 = rhs.1 * f64::from(self);
rhs
}
}

fn main() {
let mut a = A(1.0, 1.0);
a = a * 2; // is fine
a = a * 2.0; // is fine
a = a * 1 as u8; // is fine

a = 2 * a; // is fine because I did implement for i32 type
a = 2.0 * a; // impl this with generic type!
}

我能够使用通用参数 T 为我的结构 A 实现 Mul Trait,

impl<T> Mul<T> for A
where
f64: From<T>,
T: Copy,
{
type Output = A;
fn mul(mut self, rhs: T) -> Self::Output {
self.0 = self.0 * f64::from(rhs);
self.1 = self.1 * f64::from(rhs);
self
}
}

现在我可以将 A 与任何数字类型相乘,例如

A * f64A * i32

但是我无法使用通用参数实现 Mul Trait,这让我不得不这样做:

f64 * Ai32 * A

有没有什么办法可以这样实现

impl Mul<A> for i32 {
type Output = A;
fn mul(self, mut rhs: A) -> Self::Output {
rhs.0 = rhs.0 * f64::from(self);
rhs.1 = rhs.1 * f64::from(self);
rhs
}
}

但对于所有类型(泛型参数)

impl<T> Mul<A> for T { // error:type parameter `T` must be covered by another type when it appears before the first local type
type Output = A;
fn mul(self, mut rhs: A) -> Self::Output {
rhs.0 = rhs.0 * f64::from(self);
rhs.1 = rhs.1 * f64::from(self);
rhs
}
}

完整的错误:

error[E0210]: type parameter `T` must be covered by another type when it appears before the first local type (`A`)
--> src\main.rs:64:6
|
64 | impl<T> Mul<A> for T {
| ^ type parameter `T` must be covered by another type when it appears before the first local type (`A`)
|
= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type
= note: in this case, 'before' refers to the following order: `impl<..> ForeignTrait<T1, ..., Tn> for T0`, where `T0` is the first and `Tn` is the last

For more information about this error, try `rustc --explain E0210`.

最佳答案

你不能。您只能对右边的参数泛型。

图书馆通常如何解决这个问题是为 Self * T 实现它,然后根据 Self * T 创建一个实现 T* Self 的宏 显式地用 T 替换它们支持的类型列表,例如如 nalgebra :

left_scalar_mul_impl!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);

关于rust - 如何为自定义结构类型实现 Mul Trait 以两种方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70220168/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com