Rust調試

Rust調試/Debug

所有類型的要使用 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);

所有的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 絕對可以打印的,但犧牲了一些優雅。手動實現 fmt::Display 將解決這個問題。