Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fmt::Debug a number field with differing base (rust)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading