有没有办法在多个特征上实现一个特征? [英] 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
如果类型重叠,我会假设稍后会检查它.
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();
有一个不稳定的编译器特性,specialization,您可以启用它在每晚构建中,它允许您有重叠的实例,并且使用最专业"的.
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.
但是,即使启用了专业化,您的示例也不起作用,因为 A
和 B
是完全等效的,因此您永远无法明确选择一个实例.
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.
只要有一个明显更专业"的实例,它就会编译并按预期工作 - 前提是您使用的是启用了专业化的 nightly Rust 构建.例如,如果其中一个特征受到另一个特征的约束,那么它就更加专业化,所以这会起作用:
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. 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")
}
}
将实现方法指定为 default
允许另一个更具体的实现定义自己的方法版本.
Specifying the implementation method as default
allows another more specific implementation to define its own version of the method.
这篇关于有没有办法在多个特征上实现一个特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!