所有类型的要使用 std::fmt
格式化 traits
执行打印。 仅提供自动的实现类型,如在 std
库。 其他的必须以某种方式来手动实现。
fmt::Debug
trait
使这个非常简单。 所有的类型都可以 derive
(自动创建)由 fmt::Debug
实现。 这是不正确的, fmt::Display
必须手动执行。
// 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); |
{:?}
:
// 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
绝对可以打印的,但牺牲了一些优雅。手动实现 fmt::Display
将解决这个问题。