我想创建一个自定义容器,我选择了枚举而不是结构。我的目标是通过实现Neg & Sub特性使它具有数学能力。这是我尝试做的,但编译器需要进一步限制泛型T,为了使代码能够编译,我错过了什么?
use std::ops::{Neg, Sub};
#[derive(Debug)]
enum PolRec<T> {
BTuple(T, T),
Singly(T)
}
impl<T> Sub for PolRec<T>
where
T: Sub,
{
type Output = PolRec<T>;
fn sub(self, rhs: PolRec<T>) -> PolRec<T> {
match (self, rhs) {
(PolRec::BTuple(x, y), PolRec::BTuple(x2, y2)) => PolRec::BTuple(x-x2, y-y2),
(PolRec::BTuple(x, y), PolRec::Singly(t)) => PolRec::BTuple(x-t, y-t),
(PolRec::Singly(t), PolRec::BTuple(x, y)) => PolRec::BTuple(t-x, t-y),
(PolRec::Singly(t), PolRec::Singly(t2)) => PolRec::Singly(t-t2),
}
}
}
impl<T> Neg for PolRec<T>
where T: Neg,
{
type Output = PolRec<T>;
fn neg(self) -> PolRec<T> {
match self {
PolRec::BTuple(x, y) => PolRec::BTuple(-x, -y),
PolRec::Singly(t) => PolRec::Singly(-t)
}
}
}
fn main() {
let bt = PolRec::BTuple(6., 5.);
println!("{:?}", -bt);
println!("{:?}", bt-PolRec::Singly(6.));
}
1条答案
按热度按时间6kkfgxo01#
我发现这是可行的,在Sub实现块中添加特征边界Sub〈Output = T〉+ Copy,在Neg实现块中添加Neg〈Output = T〉