1

I am referencing this answer trying to print a pretty table to the console: How to print well-formatted tables to the console?

Here is my code:

fn main() {
    println!(
        "{0: <15} | {1: <15} | {2: <50}",
        "type", "human readable", "uuid id"
    );

    let characters = [
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
        's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '\n',
    ];

    for c in characters {
        println!(
            "{0:<15} | {1:<15} | {2:<50}",
            "char",
            c.escape_debug(),
            "asdfasdfdf"
        );
    }
}

Playground link.

As you can see in the playground, the table is not formatted properly. What am I doing wrong here? Why is the answer in the other question formatted correctly but mines isn't?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
l3utterfly
  • 2,106
  • 4
  • 32
  • 58
  • Try with a space between `:` and `<` and `c.escape_debug().to_string()`: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=7c1dfaf1ecf63177c6654b766fbd2956) – Jmb Sep 16 '22 at 15:15
  • 1
    @Jmb Just `to_string()` works. I'm not sure why it is needed; perhaps because the iterator returned by `escape_debug()` doesn't implement alignment. – Herohtar Sep 16 '22 at 15:15

1 Answers1

0

escape_debug() returns an instance of EscapeDebug rather than a string. Its implementation of Display doesn't seem to take the formatting spec into account. The easiest fix here is probably to use c.escape_debug().to_string() instead.

Also worth noting that as left align is the default, you shouldn't need the <. println!("{0:15} | {1:15} | {2:50}"... should be enough.

Holloway
  • 6,412
  • 1
  • 26
  • 33
  • 2
    That was my reaction too, but it doesn't fix the issue: [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=9bf16146fdc85a40cf9bd02bc8cb3b8d) – Jmb Sep 16 '22 at 15:10
  • @Jmb, good point, could have sworn it worked when I tested it. Have updated it to be (what I hope is) the real reason. – Holloway Sep 16 '22 at 15:23
  • Thanks. The `to_string` after `escape_debug` fixed the issue. This seems unintuitive to me that some implementations of Display ignores formatting for no reason. Do you think its worth to open an issue for the implementation of Display for EscapeDebug – l3utterfly Sep 17 '22 at 03:49