泛型枚举实现Rust

shyt4zoc  于 2023-03-02  发布在  其他
关注(0)|答案(1)|浏览(139)

我想创建一个自定义容器,我选择了枚举而不是结构。我的目标是通过实现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.));
}
6kkfgxo0

6kkfgxo01#

我发现这是可行的,在Sub实现块中添加特征边界Sub〈Output = T〉+ Copy,在Neg实现块中添加Neg〈Output = T〉

use std::ops::{Neg, Sub};

#[derive(Debug, Clone)]
enum PolRec<T> {
  BTuple(T, T),
  Singly(T)
}

impl<T> Sub for PolRec<T> 
where
  T: Sub + Sub<Output = T> + Copy,
{
  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 + Neg<Output = T>,
{
  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.);
  let sl = PolRec::Singly(6.);
  println!("{:?}", -sl.clone());
  println!("{:?}", bt-sl);
}

相关问题