调试(Debug)

所有的类型,若想用 std::fmt 的格式化 trait 打印出来,都要求实现这个 trait。自动的实现只为一些类型提供,比如 std 库中的类型。所有其他类型 都必须手动实现。

fmt::Debug 这个 trait 使这项工作变得相当简单。所有类型都能推导(derive,即自 动创建)fmt::Debug 的实现。但是 fmt::Display 需要手动实现。

1. // 这个结构体不能使用 `fmt::Display` 或 `fmt::Debug` 来进行打印。
2. struct UnPrintable(i32);

4. // `derive` 属性会自动创建所需的实现,使这个 `struct` 能使用 `fmt::Debug` 打印。
5. #[derive(Debug)]
6. struct DebugPrintable(i32);

所有 std 库类型都天生可以使用 {:?} 来打印:

1. // 推导 `Structure` 的 `fmt::Debug` 实现。
2. // `Structure` 是一个包含单个 `i32` 的结构体。
3. #[derive(Debug)]
4. struct Structure(i32);

6. // 将 `Structure` 放到结构体 `Deep` 中。然后使 `Deep` 也能够打印。
7. #[derive(Debug)]
8. struct Deep(Structure);

10. fn main() {
11. // 使用 `{:?}` 打印和使用 `{}` 类似。
12. println!("{:?} months in a year.", 12);
13. println!("{1:?} {0:?} is the {actor:?} name.",
14. "Slater",
15. "Christian",
16. actor="actor's");

18. // `Structure` 也可以打印!
19. println!("Now {:?} will print!", Structure(3));

21. // 使用 `derive` 的一个问题是不能控制输出的形式。
22. // 假如我只想展示一个 `7` 怎么办?
23. println!("Now {:?} will print!", Deep(Structure(7)));
24. }

所以 fmt::Debug 确实使这些内容可以打印,但是牺牲了一些美感。Rust 也通过 {:#?} 提供了 “美化打印” 的功能:

1. #[derive(Debug)]
2. struct Person<'a> {
3. name: &'a str,
4. age: u8
5. }

7. fn main() {
8. let name = "Peter";
9. let age = 27;
10. let peter = Person { name, age };

12. // 美化打印
13. println!("{:#?}", peter);
14. }

你可以通过手动实现 fmt::Display 来控制显示效果。

参见:

attributes, derive, std::fmt 和 struct