por*_*y11 6 generics traits rust
为什么这不起作用:
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")
}
}
Run Code Online (Sandbox Code Playgroud)
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")
}
}
Run Code Online (Sandbox Code Playgroud)
如果类型重叠,我会假设稍后会检查它。
你希望这个程序的输出是什么?
struct AAndB {}
impl A for AAndB {}
impl B for AAndB {}
let a_and_b = AAndB {};
a_and_b.update();
Run Code Online (Sandbox Code Playgroud)
有一个不稳定的编译器功能,specialization,您可以在夜间构建中启用它,它允许您有重叠的实例,并且使用最“专业”的。
但是,即使启用了专业化,您的示例也不起作用,因为A和B完全等效,因此您永远无法明确选择一个实例。
只要有一个明显“更专业”的实例,它就会编译并按预期工作 - 前提是您使用的是启用了专业化的 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")
}
}
Run Code Online (Sandbox Code Playgroud)
将实现方法指定为default允许另一个更具体的实现定义自己的方法版本。