Published on

Display and Debug Traits in Rust

use std::fmt;

// 自定义结构体
#[derive(Debug)] // 自动派生 Debug trait
struct Point {
    x: f32,
    y: f32,
}

// 手动实现 Display trait(用于 {})
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Point(x={:.1}, y={:.1})", self.x, self.y)  // 控制小数位数
    }
}

fn main() {
    let point = Point { x: 3.14159, y: 2.71828 };

    // 使用 Display trait({})
    println!("Display: {}", point);  // 输出: Point(x=3.1, y=2.7)

    // 使用 Debug trait({:?})
    println!("Debug: {:?}", point);  // 输出: Point { x: 3.14159, y: 2.71828 }

    // 使用 Debug 的另一种形式({:#?},带缩进)
    println!("Pretty Debug: {:#?}", point);
    /* 输出:
    Point {
        x: 3.14159,
        y: 2.71828,
    }
    */
}

THE END