Wrongly formatted error info in test

Hi, everyone, I'm still a newbie to rust and got confused when learning to write tests recently.

I‘’ve learnt 2 ways to print error info in tests, i.e., using eprintln! or simply returning an Err with an info String. Here is a simple case.

    #[test]
    fn it_works() -> Result<(), String> {
        if 2 + 2 == 3 {
            Ok(())
        } else {
            let e = String::from("\n>> ![two plus two does not equal three.]\n");
            eprintln!("{}",e);
            Err(e) // Why Not Formatted String ?
        }
    }

And the output is

It seems that the second way can NOT parse \n correctly. What' s wrong with it?
I'd appreciate it if someone could explain to me why it happened.

It's because the string is printed using Debug instead of Display. For example:

fn main() {
    let my_string = "abc\n\t\"'''{}";

    // Printing using Display
    println!("{}", my_string);

    // Printing using Debug
    println!("{:?}", my_string);
}
abc
	"'''{}
"abc\n\t\"'''{}"

When printing with Debug, the string is displayed with quotes around it and special characters are escaped.

5 Likes