Debugトレイトは、デバッグ用の文字列を取得する為のトレイト。
use std::fmt::Debug;
Debugトレイトを実装すると、println!マクロ等で"{:?}"によって出力できるようになる。
Debugトレイトは、#[derive(Debug)]属性によって実装を生成することが出来る。
#[derive(Debug)]
struct MyStruct {
value1: i32,
value2: i32,
}
fn main() {
let value = MyStruct {
value1: 123,
value2: 456,
};
println!("{:?}", value);
}
↓実行結果
MyStruct { value1: 123, value2: 456 }
Debugトレイトを独自に実装する例。
struct MyStruct {
value1: i32,
value2: i32,
}
impl std::fmt::Debug for MyStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MyStruct")
.field("value1", &self.value1)
.field("value2", &self.value2)
.finish()
}
}
fieldメソッドの呼び出しを削れば、不要な値を出力しないことが出来る。
↓実行結果
MyStruct { value1: 123, value2: 456 }
DebugトレイトからDisplayトレイトと同じ文字列を返す方法。
impl std::fmt::Debug for MyStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
Displayトレイトを実装している場合、println!マクロ等で"{}"による出力が出来るので、それを利用する。