In Rust Debug is a trait and it can be automatically implemented by using the derive syntax. This is done on a struct
and it enables debugging output showing the struct
contents.
Typically, it is best to just have the Rust compiler automatically implement Debug. This can speed up development time of Rust programs.
Consider this example program—the Test struct
is decorated with the derive Debug syntax. It is important to start the line with the "#" symbol.
struct
by specifying the code field and the values field (which is a more complex Vector
type).println
macro argument.#[derive(Debug)] struct Test { code: usize, values: Vec<u8>, } fn main() { // Step 1: Create new struct. let test = Test { code: 10, values: vec![10, 20, 30], }; // Step 2: Use debug formatting. println!("{:?}", test); // Step 3: Use pretty-print debug formatting. println!("{:#?}", test); }Test { code: 10, values: [10, 20, 30] } Test { code: 10, values: [ 10, 20, 30, ], }
Does Debug impact code size in Release builds? In a quick test, I compiled a program with the Debug trait on a struct
, and then removed it.
Using the Debug trait enables us to output the contents of structs with println
. It does not seem to make programs slower unless we add debugging calls.