簡體   English   中英

Rust 中相同類型的相同特征的多個實現

[英]Multiple implementations for the same trait of the same type in Rust

使用 Rust 特征,我可以表達一個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 }
}

我嘗試了類似函數式的方法,但該解決方案似乎依賴於在特征上添加一個額外的類型參數,而不是使用Self作為元素,這給了我一個警告。

首選的解決方案是使用標記特征進行操作——我也嘗試過但沒有成功。

正如@rodrigo 所指出的,答案是使用標記結構

以下示例顯示了一個工作片段: 操場

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))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM