简体   繁体   English

有什么方法可以在多个特征上实现一个特征?

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

Why doesn't this work: 为什么这样不起作用:

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

I would assume it is checked later if types overlap. 我认为稍后会检查类型是否重叠。

What would you expect the output of this program to be? 您希望该程序的输出是什么?

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

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

There is an unstable compiler feature, specialization , which you can enable in nightly builds, which lets you have overlapping instances, and the most "specialized" is used. 有一个不稳定的编译器功能,即specialization ,您可以在每晚的构建中启用该功能,该功能可以让您有重叠的实例,并且使用最“专业化”的功能。

But, even with specialization enabled, your example won't work because A and B are completely equivalent so you could never unambiguously pick an instance. 但是,即使启用了专业化功能,您的示例也将无法正常工作,因为AB完全等效,因此您永远不会明确选择一个实例。

As soon as there is an obviously "more specialized" instance, it will compile and work as expected - provided you are using a nightly build of Rust with specialization enabled. 只要有一个明显的“更加专业化”的实例,它将立即按预期的方式编译和运行-前提是您使用启用了专业化功能的Rust 每晚构建。 For example, if one of the traits is bounded by the other, then it is more specialized, so this would work: 例如,如果一个特征受另一个特征限制,则它更加专业化,因此可以使用:

#![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")
    }
}

Specifying the implementation method as default allows another more specific implementation to define its own version of the method. 将实现方法指定为default允许另一个更具体的实现定义其自己的方法版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM