一起定义 fmt::Display 和 fmt::Debug

Phi*_*ZXX 7 class traits rust

是否可以将fmt::Displayfmt::Debug一起定义,即它们使用相同的实现?

\n

假设我们有以下示例代码(纯粹用于演示目的):

\n
use std::fmt;\n\nstruct MyDate {\n    pub year: u16,\n    pub month: u8,\n    pub day: u8\n}\n\nimpl PartialEq for MyDate {\n    fn eq(&self, other: &Self) -> bool {\n        self.year == other.year && self.month == other.month && self.day == other.day\n    }\n}\n\nimpl fmt::Display for MyDate {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, "{}-{:02}-{:02}", self.year, self.month, self.day)\n    }\n}\n\nimpl fmt::Debug for MyDate {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, "{}", self)\n    }\n}\n\nfn main() {\n    let d1 = MyDate { year: 2008, month: 9, day: 10 };\n    let d2 = MyDate { year: 2008, month: 9, day: 10 };\n\n    println!("Date = {}", d1);  // requires fmt::Display\n    assert_eq!(d1, d2);         // requires fmt::Debug\n}\n
Run Code Online (Sandbox Code Playgroud)\n

看来,为了使用 打印我的类println并使用 编写单元测试assert_eq,我需要定义这两个fmt特征。有没有办法让 1 个“打印”实现同时定义fmt::Displayfmt::Debug?例如类似impl fmt::Debug, fmt::Display for MyDate { ... }或类似的东西?

\n

#[derive(Debug)]或者只是放在任何班级前面是常见的做法吗?如果我的问题是 na\xc3\xafve,我很抱歉,因为我是 Rust 新手。

\n

Kev*_*eid 5

大多数情况下,Display并且Debug有不同的输出。当在两种情况下使用相同的格式有意义时,您编写的代码就很好。\xe2\x80\x94也可以,#[derive(Debug)]这是你的决定。我认为要记住的重要一点是,Debug不应遗漏任何内容,并且要明确。

\n

在您展示的情况下,Display格式完全准确地显示了结构体的所有字段,因此重用来Display实现Debug. 如果您有很多这样的类型,您可以使用一个简单的宏来生成Debug转发到Display.

\n

顺便说一句,我建议使用#[derive(PartialEq)]您展示的手动 PartialEq 实现来代替。它是完全等价的,并且避免了忘记比较新添加的字段的危险故障模式。

\n