有没有办法在多个特征上实现一个特征?

Is there some way to implement a trait on multiple traits?

为什么这不起作用:

trait Update {
    fn update(&mut self);
}

trait A {}
trait B {}

impl<T: A> Update for T {
    fn update(&mut self) {
        println!("A")
    }
}

impl<U: B> Update for U {
    fn update(&mut self) {
        println!("B")
    }
}
error[E0119]: conflicting implementations of trait `Update`:
  --> src/main.rs:14:1
   |
8  | impl<T: A> Update for T {
   | ----------------------- first implementation here
...
14 | impl<U: B> Update for U {
   | ^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

如果类型重叠,我假设稍后会检查它。

您希望这个程序的输出是什么?

struct AAndB {}
impl A for AAndB {}
impl B for AAndB {}

let a_and_b = AAndB {};
a_and_b.update();

有一个不稳定的编译器功能,specialization,您可以在夜间构建中启用它,它可以让您有重叠的实例,并且使用最多 "specialized"。

但是,即使启用了专业化,您的示例也不会工作,因为 AB 是完全等价的,因此您永远无法明确选择一个实例。

只要有一个明显的 "more specialized" 实例,它就会按预期编译和工作 - 前提是您使用的是 nightly 构建的 Rust 并启用了专业化。例如,如果其中一个特征受另一个特征的限制,那么它就更专业了,所以这样可以工作:

#![feature(specialization)]

trait Update {
    fn update(&mut self);
}

trait A {}
trait B: A {}

impl<T: A> Update for T {
    default fn update(&mut self) {
        println!("A")
    }
}

impl<U: B> Update for U {
    fn update(&mut self) {
        println!("B")
    }
}

将实现方法指定为 default 允许另一个更具体的实现定义自己的方法版本。