問題一覧に戻る
中級トレイト
問題68: Display/Debugトレイト
DisplayとDebugは型を文字列に変換するフォーマット用トレイトです。Displayは{'}でユーザー向けの出力、Debugは{:?}で開発者向けの出力を提供します。Displayを実装すると型を直接出力でき、Debugは内部構造を表示してデバッグに役立ちます。型を表示可能にする基本的なトレイトです。
use std::fmt;
struct Point {
x: i32,
y: i32,
}
// Display実装
impl fmt:: for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt:: {
write!(f, "Point({}, {})", self.x, self.y)
}
}
// Debug実装
impl fmt:: for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("Point")
.field("x", &self.x)
.field("y", &self.y)
.()
}
}
fn main() {
let p = Point { x: 10, y: 20 };
// Display形式で表示
println!("Display: {}", p);
// Debug形式で表示
println!("Debug: {:?}", p);
}