Display Rust · 常用Trait
标准格式化 Trait,实现后就能用 println!("{}", x) 以人类可读形式输出。
怎么用
impl Display for 类型 { fn fmt(&self, f: &mut Formatter) -> Result { ... } },用于自定义打印
小例子
use std::fmt::Display;
struct 分数(i32);
impl Display for 分数 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}分", self.0)
}
}
println!("{}", 分数(85));
运行结果
85分
提醒:Debug 给程序员看,Display 给最终用户看
在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Rust全部词条