Rust调试/Debug
所有类型的要使用%uA0std::fmt
%uA0格式化%uA0traits
%uA0执行打印。 仅提供自动的实现类型,如在%uA0std
%uA0库。 其他的必须以某种方式来手动实现。
%uA0fmt::Debug
%uA0trait
%uA0使这个非常简单。%uA0所有的类型都可以%uA0derive
%uA0(自动创建)由%uA0fmt::Debug
%uA0实现。 这是不正确的,%uA0fmt::Display
%uA0必须手动执行。
// 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 库类型自动打印也使用%uA0{:?}
%uA0:
// 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&aposs") // `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))) }因此%uA0
fmt::Debug
%uA0绝对可以打印的,但牺牲了一些优雅。手动实现%uA0fmt::Display
%uA0将解决这个问题。