arnobpl
arnobpl

Reputation: 1216

How to use internal #[derive(Debug)] in std::fmt::Debug

I want to customize the output of a struct called FooOut but I don't want to change the debug output of the internal field FooIn which is inside FooOut. Consider the Rust code:

#[derive(Default)]
struct FooOut {
    num1: u32,
    num2: u32,
    obj: FooIn,
}

#[derive(Debug, Default)]
struct FooIn {
    bval: bool,
    list: Vec<u32>,
}

impl std::fmt::Debug for FooOut {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "FooOut {{ sum: {}, num1: {}, num2: {}, obj: {} }}",
                   self.num1 + self.num2,
                   self.num1,
                   self.num2,
                   self.obj)  // self.obj is not working without implementing it too
    }
}

In the above code, I am trying to customize the debug output of FooOut (by adding sum), but I don't want to customize/reimplement the debug output of FooIn. Is there any way to do that?

Upvotes: 1

Views: 1180

Answers (2)

arnobpl
arnobpl

Reputation: 1216

( Adding Alex Larionov's comment as the answer. )

Instead of using {} for FooIn, I need to use {:?} to use the debug output of FooIn

impl std::fmt::Debug for FooOut {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "FooOut {{ sum: {}, num1: {}, num2: {}, obj: {:?} }}",
                   self.num1 + self.num2,
                   self.num1,
                   self.num2,
                   self.obj)
    }
}

Upvotes: 2

Freyja
Freyja

Reputation: 40884

Instead of manually constructing the debug string yourself, I recommend that you use Formatter::debug_struct (or one of its sibling functions) instead:

impl std::fmt::Debug for FooOut {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("FooOut")
            .field("sum", &(self.num1 + self.num2))
            .field("num1", &self.num1)
            .field("num2", &self.num2)
            .field("obj", &self.obj)
            .finish()
    }
}

Playground example

This is what #[derive(Debug)] is using to build the default debug string for an object. This also has the added advantage that you get both the compact debug string with {:?} and the alternative, expanded debug string with {:#?}.

Upvotes: 6

Related Questions