调试
所有想要使用 std::fmt
格式化 trait
的类型都需要实现可打印接口。自动实现仅针对 std
库中的类型提供。所有其他类型都必须以某种方式手动实现。
fmt::Debug
trait
使这变得非常简单。所有类型都可以derive
(自动创建)fmt::Debug
实现。但这不适用于 fmt::Display
,它必须手动实现。
#![allow(unused)] fn main() { // This structure cannot be printed either with `fmt::Display` or // with `fmt::Debug`. struct UnPrintable(i32); // The `derive` attribute automatically creates the implementation // required to make this `struct` printable with `fmt::Debug`. #[derive(Debug)] struct DebugPrintable(i32); }
所有 std
库类型也可以使用 {:?}
自动打印
// Derive the `fmt::Debug` implementation for `Structure`. `Structure` // is a structure which contains a single `i32`. #[derive(Debug)] struct Structure(i32); // Put a `Structure` inside of the structure `Deep`. Make it printable // also. #[derive(Debug)] struct Deep(Structure); fn main() { // Printing with `{:?}` is similar to with `{}`. println!("{:?} months in a year.", 12); println!("{1:?} {0:?} is the {actor:?} name.", "Slater", "Christian", actor="actor's"); // `Structure` is printable! println!("Now {:?} will print!", Structure(3)); // The problem with `derive` is there is no control over how // the results look. What if I want this to just show a `7`? println!("Now {:?} will print!", Deep(Structure(7))); }
因此,fmt::Debug
肯定可以使其可打印,但牺牲了一些优雅性。Rust 还通过 {:#?}
提供“漂亮打印”。
#[derive(Debug)] struct Person<'a> { name: &'a str, age: u8 } fn main() { let name = "Peter"; let age = 27; let peter = Person { name, age }; // Pretty print println!("{:#?}", peter); }
可以手动实现 fmt::Display
来控制显示。