如何在类型已经实现 Display 的特征对象上实现 Display

How to implement Display on a trait object where the types already implement Display

我有一些代码 return 是类型 MyTrait 的特征对象,因此它可以 return 几个不同的结构之一。我想为 trait 对象实现 Display trait,这样我就可以打印对象,并将详细信息委托给各种结构,因为它们每个都需要自己的自定义格式化程序。

我可以通过将格式化方法作为 MyTrait 定义的一部分,然后为 MyTrait 实现 Display 并委托 - 像这样:

来实现这一点
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)
    }
}

但是,我已经为每个实现 MyTrait 的结构实现了 Display 特性。这意味着我最终为每个结构提供了两种方法,它们做同样的事情 - fmt() 方法直接在结构上满足 Display 特征,以及 my_fmt() 方法被调用上面的代码。这看起来笨拙且重复。有更简单的方法吗?

这里有一个完整的示例程序来说明这一点。它比我希望的要长一点(它基于我之前问题 的答案),但我想不出更简单的方法来说明这一点。当然,在这个玩具示例中,结构和 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
    }
}

谁能推荐一种更简单、更简洁的方法来做到这一点?

您可以使 Display 成为 MyTrait 的超级特征。

trait MyTrait: fmt::Display {
    fn is_even(&self) -> bool;
}

这将使 MyTrait 的特征对象成为 Display。这仅在您希望 MyTrait 的所有实现者都实现 Display 时有效,但在您之前的解决方案中也是如此。