Rust中相同类型的相同trait的多个实现



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

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

然后,我也可以为字符串或整数实现trait:

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

我尝试了一些功能,但解决方案似乎依赖于在trait上有一个额外的类型参数,而不是使用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))
}

最新更新