Home
Map
Debug Example (derive Debug)Use the derive Debug syntax to automatically implement debugging output functions for println.
Rust
This page was last reviewed on Jul 4, 2023.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 4, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.