为什么这不起作用:
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();
有一个不稳定的编译器功能,专业化,您可以在夜间构建中启用它,这可以让您拥有重叠的实例,并且使用最“专业”的实例。
但是,即使启用了专业化,您的示例也无法工作,因为A
and B
是完全等价的,所以你永远无法明确地选择一个实例。
一旦出现明显“更专业”的实例,它就会按预期进行编译和工作 - 前提是您使用的是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
允许另一个更具体的实现来定义它自己的方法版本。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)