Suggestion for helper for writing `fmt::Debug` impls with nested structure

Another option would be to offer just a helper function, without the need for the larger API in the form of a struct. I’m imagining:

use std::fmt;

pub fn display_with(f: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl fmt::Display {
    struct DisplayWith<F>(F);

    impl<F> fmt::Display for DisplayWith<F>
    where
        F: Fn(&mut fmt::Formatter) -> fmt::Result,
    {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            self.0(f)
        }
    }

    DisplayWith(f)
}

pub fn debug_with(f: impl Fn(&mut fmt::Formatter) -> fmt::Result) -> impl fmt::Debug {
    struct DebugWith<F>(F);

    impl<F> fmt::Debug for DebugWith<F>
    where
        F: Fn(&mut fmt::Formatter) -> fmt::Result,
    {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            self.0(f)
        }
    }

    DebugWith(f)
}

[The display version can be useful for functions that want to return some form of impl Display value (which some API may prefer over generating a String).]

2 Likes