我遇到的情况是,我的几个 struct 应该实现多个特性,但它们都至少实现了一个共同的特性.当我得到这些 struct 的混合包时,我想把它们都视为共同特征:将它们作为键入该特征的方法参数传递,存储在为该特征键入的集合中,等等.
我还不知道怎么做.下面是一些代码,我try 按照这里建议的方式执行,但未能编译:
trait ThingWithKeys {
fn use_keys (&self) -> String;
}
//////
trait CorrectionsOfficer {
fn hitch_up_pants (&self) -> String;
}
trait CorrectionsOfficerWithKeys: ThingWithKeys + CorrectionsOfficer {}
struct CorrectionsOfficerReal {}
impl ThingWithKeys for CorrectionsOfficerReal {
fn use_keys (&self) -> String {
String::from ("Clank, clank")
}
}
impl CorrectionsOfficer for CorrectionsOfficerReal {
fn hitch_up_pants (&self) -> String {
String::from ("Grunt")
}
}
impl <T: ThingWithKeys + CorrectionsOfficer> CorrectionsOfficerWithKeys for T {}
//////
trait Piano {
fn close_lid (&self) -> String;
}
trait PianoWithKeys: Piano + ThingWithKeys {}
struct PianoReal {}
impl ThingWithKeys for PianoReal {
fn use_keys (&self) -> String {
String::from ("Tinkle, tinkle")
}
}
impl Piano for PianoReal {
fn close_lid (&self) -> String {
String::from ("Bang!")
}
}
impl <T: ThingWithKeys + Piano> PianoWithKeys for T {}
//////
trait Florida {
fn hurricane (&self) -> String;
}
trait FloridaWithKeys: ThingWithKeys + Florida {}
struct FloridaReal {}
impl ThingWithKeys for FloridaReal {
fn use_keys (&self) -> String {
String::from ("Another margarita, please")
}
}
impl Florida for FloridaReal {
fn hurricane (&self) -> String {
String::from ("Ho-hum...")
}
}
impl <T: ThingWithKeys + Florida> FloridaWithKeys for T {}
//////
fn main() {
let corrections_officer_ref: &CorrectionsOfficerWithKeys = &CorrectionsOfficerReal {};
let piano_ref: &PianoWithKeys = &PianoReal {};
let florida_ref: &FloridaWithKeys = &FloridaReal {};
use_keys (corrections_officer_ref);
use_keys (piano_ref);
use_keys (florida_ref);
}
fn use_keys (thing_with_keys: &ThingWithKeys) {
println! ("{}", thing_with_keys.use_keys ());
}
以下是编译错误:
Compiling playground v0.0.1 (file:///playground)
error[E0308]: mismatched types
--> src/main.rs:80:19
|
80 | use_keys (corrections_officer_ref);
| ^^^^^^^^^^^^^^^^^^^^^^^ expected trait `ThingWithKeys`, found trait `CorrectionsOfficerWithKeys`
|
= note: expected type `&ThingWithKeys`
found type `&CorrectionsOfficerWithKeys`
error[E0308]: mismatched types
--> src/main.rs:81:19
|
81 | use_keys (piano_ref);
| ^^^^^^^^^ expected trait `ThingWithKeys`, found trait `PianoWithKeys`
|
= note: expected type `&ThingWithKeys`
found type `&PianoWithKeys`
error[E0308]: mismatched types
--> src/main.rs:82:19
|
82 | use_keys (florida_ref);
| ^^^^^^^^^^^ expected trait `ThingWithKeys`, found trait `FloridaWithKeys`
|
= note: expected type `&ThingWithKeys`
found type `&FloridaWithKeys`
error: aborting due to 3 previous errors
本质上,它仍然无法在XxxWithKeys实现中找到ThingWithKeys实现.