Home
Rust
Debug Example (derive Debug)
Updated Jul 4, 2023
Dot Net Perls
Debug. 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.
struct
Example code. Consider this example program—the Test struct is decorated with the derive Debug syntax. It is important to start the line with the "#" symbol.
Step 1 We create a new Test struct by specifying the code field and the values field (which is a more complex Vector type).
vec
Step 2 We use debug formatting by specifying the ":?" characters in the println macro argument.
Step 3 We use pretty-printing by specifying a "#" character in the macro here. This results in more newlines and indentation.
#[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, ], }
Code size. 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.
Result No change in code size was observed. So the compiler eliminated the unused debug trait methods.
Thus It is acceptable to leave the Debug trait in a program, as it does not adversely impact code size or runtime unless we do debug output.
println
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jul 4, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen