独立的通用函数
将默认实现推迟到一个独立的泛型函数:
fn say_hello<T: Trait + ?Sized>(t: &T) {
println!("Hello I am default")
}
trait Trait {
fn say_hello(&self) {
say_hello(self);
}
}
struct Normal;
impl Trait for Normal {}
struct Special(bool);
impl Trait for Special {
fn say_hello(&self) {
if self.0 {
println!("Hey I am special")
} else {
say_hello(self)
}
}
}
fn main() {
let normal = Normal;
normal.say_hello(); // default
let special = Special(false);
special.say_hello(); // default
let special = Special(true);
special.say_hello(); // special
}
操场
两个默认特征方法
另一种方法可能是定义两个特征方法,一个作为默认实现,另一个遵循默认实现,除非它被覆盖:
trait Trait {
fn say_hello_default(&self) {
println!("Hello I am default");
}
fn say_hello(&self) {
self.say_hello_default();
}
}
struct Normal;
impl Trait for Normal {}
struct Special(bool);
impl Trait for Special {
fn say_hello(&self) {
if self.0 {
println!("Hey I am special");
} else {
self.say_hello_default();
}
}
}
fn main() {
let normal = Normal;
normal.say_hello(); // default
let special = Special(false);
special.say_hello(); // default
let special = Special(true);
special.say_hello(); // special
}
操场
默认关联常量
虽然这有点笨拙,但如果默认实现和专用实现之间的差异减少到const
值,那么您可以为您的 trait 使用默认关联const
的 trait 项:
trait Trait {
const MSG: &'static str = "Hello I am default";
fn say_hello(&self) {
println!("{}", Self::MSG);
}
}
struct Normal;
impl Trait for Normal {}
struct Special(bool);
impl Trait for Special {
const MSG: &'static str = "Hey I am special";
fn say_hello(&self) {
let msg = if self.0 {
Self::MSG
} else {
<Normal as Trait>::MSG
};
println!("{}", msg);
}
}
fn main() {
let normal = Normal;
normal.say_hello(); // default
let special = Special(false);
special.say_hello(); // default
let special = Special(true);
special.say_hello(); // special
}
操场
通过 AsRef 调用默认实现
如果唯一不同Special
的Normal
是一些额外的字段,并且Special
类型可以作为 a 运行,Normal
那么您可能希望实现AsRef<Normal>
forSpecial
并以这种方式调用默认实现:
trait Trait {
fn say_hello(&self) {
println!("Hello I am default");
}
}
struct Normal;
impl Trait for Normal {}
struct Special(bool);
impl AsRef<Normal> for Special {
fn as_ref(&self) -> &Normal {
&Normal
}
}
impl Trait for Special {
fn say_hello(&self) {
if self.0 {
println!("Hey I am special");
} else {
<Normal as Trait>::say_hello(self.as_ref());
}
}
}
fn main() {
let normal = Normal;
normal.say_hello(); // default
let special = Special(false);
special.say_hello(); // default
let special = Special(true);
special.say_hello(); // special
}
操场
默认宏实现
像往常一样,如果一切都失败了,让你的代码干燥的最暴力的方法是使用宏:
macro_rules! default_hello {
() => {
println!("Hello I am default");
}
}
trait Trait {
fn say_hello(&self) {
default_hello!();
}
}
struct Normal;
impl Trait for Normal {}
struct Special(bool);
impl Trait for Special {
fn say_hello(&self) {
if self.0 {
println!("Hey I am special");
} else {
default_hello!();
}
}
}
fn main() {
let normal = Normal;
normal.say_hello(); // default
let special = Special(false);
special.say_hello(); // default
let special = Special(true);
special.say_hello(); // special
}
操场