How is Fmt::Display 'Cleaner' than Fmt::Debug?

Viewed 107

So I'm currently getting started with Rust, and am reading my way through Rust By Example.
Doing the Exercises, and playing with the code as I go.

But in the RBE Display function description it describes Fmt::Display as 'cleaner' than Fmt::Debug.
How is this? From what I see, you have to do more work, and write more code to try and make Fmt::Display work, while Fmt::Debug works right off the bat?

Am I misunderstanding something about what 'Cleaner' Code is, or is this a typo?

1 Answers

Display's output is usually cleaner than Debug's, not the code to implement it. Debug's output is intended to be used for debug purposes, providing a less ambiguous output. Display's output is for user-facing output, so it's highly dependent on the meaning of your structure and that's why it cannot be derived.

For example, consider the following code:

fn main() {
    // Note that \t is the TAB character
    let output = "N\tO\tI\tC\tE";
    println!("Debug: {:?}", output);
    println!("Display: {}", output);
}

It will output:

Debug: "N\tO\tI\tC\tE"
Display: N  O   I   C   E

In this case, Debug will show the characters that the str (text) contains (as its more useful when debugging), while Display will just print them.

Related