我有一個(gè)特質(zhì)Sleep:pub trait Sleep { fn sleep(&self);}我可以為每個(gè)結(jié)構(gòu)提供不同的睡眠實(shí)現(xiàn)方式,但事實(shí)證明,大多數(shù)人以很少的方式睡眠。您可以在床上睡覺: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() }}有一些奇怪的情況。我有一個(gè)可以睡在墻上的朋友,但是大多數(shù)情況下,大多數(shù)人會遇到一些簡單的情況。我們定義一些結(jié)構(gòu),然后讓它們?nèi)胨簊truct 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`該編譯器錯誤很奇怪,因?yàn)槿绻硞€(gè)特性實(shí)現(xiàn)了另一個(gè)特性時(shí)出現(xiàn)了問題,我希望在做完該特性時(shí)能早點(diǎn)聽到,而不是在嘗試使用結(jié)果時(shí)在程序的最底層。在此示例中,只有2個(gè)結(jié)構(gòu)和2種睡眠方式,但是在一般情況下,有許多結(jié)構(gòu)和幾種睡眠方式(但不如結(jié)構(gòu)體那么多)。A Bed主要是針對的實(shí)現(xiàn)Sleep,但在一般情況下,a Bed有很多用途,并且可以實(shí)現(xiàn)很多事情。唯一立即顯而易見的方法是將其轉(zhuǎn)換impl Sleep for...為可構(gòu)造自身使用的宏,但這似乎很麻煩而且很糟糕。
- 2 回答
- 0 關(guān)注
- 684 瀏覽
添加回答
舉報(bào)
0/150
提交
取消