Own Display implementation to respect Formatter width

use std::fmt::Display;

struct Bla;

impl Display for Bla {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        //println!("{:?}", f.width());  // Some(30)
        //f.write_str("Bla")            // same result!
        write!(f, "Bla")
    }
}

fn main() {
    println!("expected: {}", format_args!("'{:>30}'", "Bla"));
    println!("actual: '{:>30}'", Bla {});
}

(Playground)

I would like to display my own struct wrt to width parameters, but they are completely ignored.

You need to do the formatting yourself or instruct the formatter to do it for you, e.g. using pad.

2 Likes

The easiest approach in this specific case is probably to call "Bla".fmt(f) directly: Rust Playground


Edit: Nevermind, I suppose the option of using pad as described above, seems even nicer. Which is also what the Display implementation for str does.

But calling fmt() on the thing to be formatted is a good general approach for transparently delegating to some other display/debug/... implementation, and it's what the Display implementation for & does.

These two together are what generates the behavior for &str that you observe in your format_args!("'{:>30}'", "Bla") call.

1 Like

@jer @steffahn thanks guys for all the helpful hints! :+1:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.