209 字
1 分钟
Rust Debug Macro
The :#?
in the debug macro is a formatting specifier in Rust that provides pretty-printing for debug output. Let’s break it down:
:
indicates that a formatting specifier follows.#
enables alternate formatting, which often results in more verbose or “pretty” output.?
invokes theDebug
trait for formatting.
When combined, :#?
tells Rust to use the pretty-print format for the debug representation of the value. This is particularly useful when debugging complex structures, as it prints them in a more readable, multi-line format with proper indentation.
Here’s a quick example to illustrate the difference:
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: "Alice".to_string(),
age: 30,
};
// Using {}
// println!("Regular print: {}", person);
// This would result in an error because the Person struct doesn't implement the Display trait.
// Using :?
println!("Regular debug: {:?}", person);
// Using :#?
println!("Pretty debug: {:#?}", person);
}
This would output something like:
Regular debug: Person { name: "Alice", age: 30 }
Pretty debug: Person {
name: "Alice",
age: 30,
}
As you can see, :#?
provides a more readable, structured output, which is especially helpful when dealing with larger or more complex data structures.
Would you like me to explain any other aspects of this debug macro or Rust formatting?
Rust Debug Macro
https://blog.lpkt.cn/posts/rust-debug-macro/