I want to the Debug format of a struct number field to show a decimal value and a hexadecimal value.
So given rust struct (rust playground)
#[derive(Default)]
pub struct S1 {
pub num1: u64,
}
fn main() {
let mut s1 = S1::default();
s1.num1 = 0xFF;
println!("{:?}", s1)
}
I would like fmt::Debug implementation (i.e. format string "{:?}") to show two different based values for field num1, i.e. to print
S1 { num1: 255 (0xFF) }
(I’m not sure how to solve the easier problem: format the numeric field as hexadecimal).
Here is what I have for fmt::Debug implementation
impl std::fmt::Debug for S1 {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("S1")
.field("num1", &self.num1)
.finish()
}
}
I do not know which part of std::fmt module would help me.
>Solution :
You can use format_args! to construct the formatting arguments in a low-cost way:
impl std::fmt::Debug for S1 {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("S1")
.field("num1", &format_args!("{0:?} (0x{0:X})", &self.num1))
.finish()
}
}