Menu
CoddyTech

Display Trait

本课属于 Coddy Rust 学习旅程的“面向对象编程”单元。第 36 课,共 61 课。

虽然 Debug 非常适合开发者检查数据,但 Display trait 是为面向用户的输出设计的。它为 println! 中的 {} 格式化器提供支持。与 Debug 不同,Rust 无法自动派生 Display。你必须手动实现它。

要实现 Display,你需要引入 fmt 模块并实现 fmt 方法:

use std::fmt;

struct Temperature {
    celsius: f64,
}

impl fmt::Display for Temperature {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}°C", self.celsius)
    }
}

fmt 方法接收一个 Formatter,并返回一个 fmt::Result。你可以使用 write! 宏来格式化输出,并通过 self 访问结构体的字段。

现在,你可以使用标准的 {} 格式化器打印这个结构体:

let temp = Temperature { celsius: 23.5 };
println!("{}", temp);  // 23.5°C

关键区别:Debug 输出会显示数据的结构(有助于调试),而 Display 输出经过了美化,面向最终用户。一个结构体可以同时实现两者:调试时使用 {:?},简洁输出时使用 {}。

challenge icon

挑战

简单

让我们创建一个方便用户使用的商品展示系统!Debug 会显示数据的原始结构,而 Display trait 可以让你打造精美、易读的输出内容,非常适合最终用户。

你需要将代码分到两个文件中:

  • product.rs:定义一个包含两个公开字段的公开 Product 结构体:name(String)和 price(f64)。为这个结构体实现 Display trait,使其格式为 {name} - ${price}。记得引入 std::fmt,并在 fmt 方法中使用 write! 宏。
  • main.rs:引入 product 模块,并使用提供的输入创建一个 Product 实例。使用标准的 {} 格式化符打印商品,显示自定义的展示内容。

Display trait 要求你手动实现 fmt 方法:Rust 无法像派生 Debug 那样自动派生它。这样你就能完全控制类型向用户呈现的方式。

你的输出应以清晰、易读的格式显示商品:

{name} - ${price}

例如,输入 Wireless Mouse 和 29.99 时:

Wireless Mouse - $29.99

你会收到两个输入:商品名称和价格(将其解析为 f64)。

亲手试试

mod product;

use product::Product;

fn main() {
    let mut name = String::new();
    std::io::stdin().read_line(&mut name).expect("Failed to read line");
    let name = name.trim().to_string();

    let mut price_input = String::new();
    std::io::stdin().read_line(&mut price_input).expect("Failed to read line");
    let price: f64 = price_input.trim().parse().expect("Failed to parse price");

    // TODO:用名称和价格创建一个 Product 实例

    // TODO:使用 {} 格式化输出产品
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: Rust 在线编译器