是否可以一起定義fmt::Display和定義fmt::Debug,即它們使用相同的實作?
假設我們有以下示例代碼(僅用于演示目的):
use std::fmt;
struct MyDate {
pub year: u16,
pub month: u8,
pub day: u8
}
impl PartialEq for MyDate {
fn eq(&self, other: &Self) -> bool {
self.year == other.year && self.month == other.month && self.day == other.day
}
}
impl fmt::Display for MyDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}-{:02}-{:02}", self.year, self.month, self.day)
}
}
impl fmt::Debug for MyDate {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
fn main() {
let d1 = MyDate { year: 2008, month: 9, day: 10 };
let d2 = MyDate { year: 2008, month: 9, day: 10 };
println!("Date = {}", d1); // requires fmt::Display
assert_eq!(d1, d2); // requires fmt::Debug
}
似乎為了使用 列印我的類println并使用撰寫單元測驗assert_eq,我需要定義這兩個fmt特征。有沒有辦法讓 1 個“列印”實作同時定義fmt::Display和fmt::Debug?例如類似impl fmt::Debug, fmt::Display for MyDate { ... }或類似的東西?
或者只是放在#[derive(Debug)]任何班級前面是常見的做法嗎?如果我的問題很幼稚,請道歉,因為我是 Rust 新手。
uj5u.com熱心網友回復:
在大多數情況下,Display并Debug有不同的輸出。如果在這兩種情況下都可以使用相同的格式,那么您撰寫的代碼就很好。也可以#[derive(Debug)]——這是你的決定。我認為要記住的重要一點是不Debug應該遺漏任何東西,并且要明確。
在您展示的情況下,Display格式完全準確地顯示了結構的所有欄位,因此重Display用來實作Debug. 如果你有很多這樣的型別,你可以使用一個簡單的宏來生成Debug轉發到Display.
順便說一句,我建議您使用#[derive(PartialEq)]而不是您展示的手動 PartialEq 實作。它是完全等效的,并且避免了忘記比較新添加的欄位的危險失敗模式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/357437.html
上一篇:OOP-理解繼承
下一篇:需要在另一個類中實作
