[英]How does trait specialization actually work?
I tried to specialize a trait, and it fails to compile because of "conflicting implementations". 我试图专门研究一个特性,由于“冲突的实现”而无法编译。 But my understanding of specialization is that more specific implementations should override more generic ones.
但是我对专业化的理解是,更具体的实现应优先于更通用的实现。 Here is a very basic example:
这是一个非常基本的示例:
mod diving {
pub struct Diver<T> {
inner: T
}
}
mod swimming {
use diving;
pub trait Swimmer {
fn swim(&self) {
println!("swimming")
}
}
impl<T> Swimmer for diving::Diver<T> {
}
}
mod drowning {
use diving;
use swimming;
impl swimming::Swimmer for diving::Diver<&'static str> {
fn swim(&self) {
println!("drowning, help!")
}
}
}
fn main() {
let x = diving::Diver::<&'static str> {
inner: "Bob"
};
x.swim()
}
The error is: 错误是:
rustc 1.18.0 (03fc9d622 2017-06-06)
error[E0119]: conflicting implementations of trait `swimming::Swimmer` for type `diving::Diver<&'static str>`:
--> <anon>:23:5
|
15 | / impl<T> Swimmer for diving::Diver<T> {
16 | |
17 | | }
| |_____- first implementation here
...
23 | / impl swimming::Swimmer for diving::Diver<&'static str> {
24 | | fn swim(&self) {
25 | | println!("drowning, help!")
26 | | }
27 | | }
| |_____^ conflicting implementation for `diving::Diver<&'static str>`
I would have expected that the more specific drowning implementation with an actual type of &'static str
would allow specialized implementation, but instead it fails to compile. 我本来希望具有实际类型的
&'static str
的更具体的溺水实现将允许专门的实现,但是相反,它无法编译。
Specialization is not yet stabilized. 专业化尚未稳定。 You need to use nightly build of Rust and enable specialization by adding
#![feature(specialization)]
in the first line. 您需要使用Rust的每晚构建,并通过在第一行中添加
#![feature(specialization)]
来启用专业化。
Then you'll need to fix two minor errors in your code (private inner
field and lack of use swimming::Swimmer;
), but that is straightforward. 然后,您需要修复代码中的两个小错误(私有
inner
字段和缺少use swimming::Swimmer;
),但这很简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.