特质专业化实际上是如何运作的?
How does trait specialization actually work?
我试图专门化一个特征,但由于 "conflicting implementations" 而无法编译。但我对专业化的理解是,更具体的实现应该覆盖更通用的实现。这是一个非常基本的例子:
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()
}
错误是:
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>`
我原以为具有实际类型 &'static str
的更具体的淹没实现将允许专门的实现,但它无法编译。
专精尚未稳定。您需要使用每晚构建的 Rust 并通过在第一行添加 #![feature(specialization)]
来启用专业化。
然后您需要修复代码中的两个小错误(私有 inner
字段和缺少 use swimming::Swimmer;
),但这很简单。
我试图专门化一个特征,但由于 "conflicting implementations" 而无法编译。但我对专业化的理解是,更具体的实现应该覆盖更通用的实现。这是一个非常基本的例子:
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()
}
错误是:
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>`
我原以为具有实际类型 &'static str
的更具体的淹没实现将允许专门的实现,但它无法编译。
专精尚未稳定。您需要使用每晚构建的 Rust 并通过在第一行添加 #![feature(specialization)]
来启用专业化。
然后您需要修复代码中的两个小错误(私有 inner
字段和缺少 use swimming::Swimmer;
),但这很简单。