我有一些代码返回类型的特征对象MyTrait
这样它就可以返回几个不同的结构之一。我想实施Display
特征对象的特征,以便我可以打印该对象,并将详细信息委托给各种结构,因为它们每个都需要自己的自定义格式化程序。
我可以通过将格式化方法作为其中的一部分来实现这一点MyTrait
定义,然后实现Display
for MyTrait
并委派 - 像这样:
trait MyTrait {
fn is_even(&self) -> bool;
fn my_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
impl fmt::Display for MyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.my_fmt(f)
}
}
不过,我已经有了Display
为每个实现的结构实现的特征MyTrait
。这意味着我最终为每个结构提供了两种执行相同操作的方法 -fmt()
方法来满足Display
直接在结构上的特征,并且my_fmt()
上面的代码调用的方法。这看起来很笨拙且重复。有更简单的方法吗?
这是一个完整的示例程序来说明这一点。它比我想要的要长一点(它基于我之前问题的答案调用返回具有共享特征的不同类型并传递给其他函数的函数 https://stackoverflow.com/questions/54470036/calling-functions-which-return-different-types-with-shared-trait-and-pass-to-oth/54470897),但我想不出更简单的方法来说明这一点。当然,在这个玩具示例中,结构体和fmt
功能非常简单;在我的实际应用中它们更加复杂。
use std::fmt;
trait MyTrait {
fn is_even(&self) -> bool;
fn my_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result;
}
struct First {
v: u8,
}
struct Second {
v: Vec<u8>,
}
impl MyTrait for First {
fn is_even(&self) -> bool {
self.v % 2 == 0
}
fn my_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.v)
}
}
impl MyTrait for Second {
fn is_even(&self) -> bool {
self.v[0] % 2 == 0
}
fn my_fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.v[0])
}
}
fn make1() -> First {
First { v: 5 }
}
fn make2() -> Second {
Second { v: vec![2, 3, 5] }
}
// Implement Display for the structs and for MyTrait
impl fmt::Display for First {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.v)
}
}
impl fmt::Display for Second {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.v[0])
}
}
impl fmt::Display for MyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.my_fmt(f)
}
}
fn requires_mytrait<T: MyTrait + ?Sized>(v: &&T) {
println!("{:?}", v.is_even());
}
fn main() {
for i in 0..2 {
let v1;
let v2;
let v = match i {
0 => {
v1 = make1();
println!("> {}", v1); // Demonstrate that Display
// is implemented directly
// on the type.
&v1 as &MyTrait
}
_ => {
v2 = make2();
println!("> {}", v2); // Demonstrate that Display
// is implemented directly
// on the type.
&v2 as &MyTrait
}
};
requires_mytrait(&v);
println!("{}", v); // Here I print the trait object
}
}
谁能建议一种更简单、更干净的方法来做到这一点?