Rust 中相同类型的相同特征的多个实现

Multiple implementations for the same trait of the same type in Rust

使用 Rust traits,我可以表达一个 Monoid 类型 class(请原谅我对方法的命名):

trait Monoid {
  fn append(self, other: Self) -> Self;
  fn neutral() -> Self;
}

然后,我也可以实现字符串或整数的特征:

impl Monoid for i32 {
  fn append(self, other: i32) -> i32 {
    self + other
  }
  fn neutral() -> Self { 0 }
}

但是,我现在如何在 i32 上为乘法案例添加另一个实现?

impl Monoid for i32 {
  fn append(self, other: i32) -> i32 {
    self * other
  }
  fn neutral() { 1 }
}

我尝试了类似 functional 中所做的事情,但该解决方案似乎依赖于在特征上有一个额外的类型参数,而不是对元素使用 Self,这给了我一个警告.

首选的解决方案是对操作使用标记特征 - 我也尝试过但没有成功。

正如@rodrigo 指出的那样,答案是使用标记结构

以下示例显示了一个工作片段:playground

trait Op {}
struct Add;
struct Mul;
impl Op for Add {}
impl Op for Mul {}

trait Monoid<T: Op>: Copy {
    fn append(self, other: Self) -> Self;
    fn neutral() -> Self;
}

impl Monoid<Add> for i32 {
    fn append(self, other: i32) -> i32 {
        self + other
    }
    fn neutral() -> Self {
        0
    }
}

impl Monoid<Mul> for i32 {
    fn append(self, other: i32) -> i32 {
        self * other
    }
    fn neutral() -> Self {
        1
    }
}

pub enum List<T> {
    Nil,
    Cons(T, Box<List<T>>),
}

fn combine<O: Op, T: Monoid<O>>(l: &List<T>) -> T {
    match l {
        List::Nil => <T as Monoid<O>>::neutral(),
        List::Cons(h, t) => h.append(combine(&*t)),
    }
}

fn main() {
    let list = List::Cons(
        5,
        Box::new(List::Cons(
            2,
            Box::new(List::Cons(
                4,
                Box::new(List::Cons(
                    5,
                    Box::new(List::Cons(-1, Box::new(List::Cons(8, Box::new(List::Nil))))),
                )),
            )),
        )),
    );
    
    println!("{}", combine::<Add, _>(&list));
    println!("{}", combine::<Mul, _>(&list))
}