Format string to print formatted table in console

Viewed 34

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?

1 Answers

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.

Related