阅读后this ,我也会有一个关于重载数学运算符的类似问题。
考虑到此代码基础,假设 T
对象可以按值添加并给出 O
:
use std::ops::Add;
struct NoCopy<T>(T);
impl<T: Add<Output = O>, O> Add for NoCopy<T> {
type Output = NoCopy<O>;
fn add(self, other: Self) -> Self::Output {
NoCopy(self.0 + other.0)
}
}
fn main() {
let a = NoCopy::<isize>(5);
let b = NoCopy::<isize>(3);
let _c = a + b;
}
我想提供一个 Add 特征的实现来处理 &NoCopy<T>
并提供 NoCopy<O>
例如,假设为 &T
提供了 Add 运算符(并给出 O
)。 T
不需要尊重Copy
特质。
但我不知道如何编写它,尤其是泛型绑定(bind)。
impl<???> Add for &NoCopy<T> {
type Output = NoCopy<O>;
fn add(self, other: Self) -> Self::Output {
NoCopy(&self.0 + &other.0)
}
}
缺失的部分( ???
)会是什么样子?
最佳答案
您可以对 &T
设置生命周期约束:
impl<'a, T: 'a, O> Add for &'a NoCopy<T>
where
&'a T: Add<Output = O>,
{
type Output = NoCopy<O>;
fn add(self, other: Self) -> Self::Output {
NoCopy(&self.0 + &other.0)
}
}
( playground )
关于generics - 通用数学运算符重载而不进行复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64592298/