我有一个特质Sleep:
pub trait Sleep {
fn sleep(&self);
}
我可以为每个结构提供不同的睡眠实现方式,但事实证明,大多数人以很少的方式睡眠。您可以在床上睡觉:
pub trait HasBed {
fn sleep_in_bed(&self);
fn jump_on_bed(&self);
}
impl Sleep for HasBed {
fn sleep(&self) {
self.sleep_in_bed()
}
}
如果您在露营,则可以在帐篷里睡觉:
pub trait HasTent {
fn sleep_in_tent(&self);
fn hide_in_tent(&self);
}
impl Sleep for HasTent {
fn sleep(&self) {
self.sleep_in_tent()
}
}
有一些奇怪的情况。我有一个可以睡在墙上的朋友,但是大多数情况下,大多数人会遇到一些简单的情况。
我们定义一些结构,然后让它们入睡:
struct Jim;
impl HasBed for Jim {
fn sleep_in_bed(&self) {}
fn jump_on_bed(&self) {}
}
struct Jane;
impl HasTent for Jane {
fn sleep_in_tent(&self) {}
fn hide_in_tent(&self) {}
}
fn main() {
use Sleep;
let jim = Jim;
jim.sleep();
let jane = Jane;
jane.sleep();
}
哦!编译错误:
error[E0599]: no method named `sleep` found for type `Jim` in the current scope
--> src/main.rs:44:9
|
27 | struct Jim;
| ----------- method `sleep` not found for this
...
44 | jim.sleep();
| ^^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `sleep`, perhaps you need to implement it:
candidate #1: `Sleep`
error[E0599]: no method named `sleep` found for type `Jane` in the current scope
--> src/main.rs:47:10
|
34 | struct Jane;
| ------------ method `sleep` not found for this
...
47 | jane.sleep();
| ^^^^^
|
= help: items from traits can only be used if the trait is implemented and in scope
= note: the following trait defines an item `sleep`, perhaps you need to implement it:
candidate #1: `Sleep`
该编译器错误很奇怪,因为如果某个特性实现了另一个特性时出现了问题,我希望在做完该特性时能早点听到,而不是在尝试使用结果时在程序的最底层。
在此示例中,只有2个结构和2种睡眠方式,但是在一般情况下,有许多结构和几种睡眠方式(但不如结构体那么多)。
A Bed主要是针对的实现Sleep,但在一般情况下,a Bed有很多用途,并且可以实现很多事情。
唯一立即显而易见的方法是将其转换impl Sleep for...为可构造自身使用的宏,但这似乎很麻烦而且很糟糕。