Newline escape character behavior different

#[derive(Debug)]
struct A {
    des: String
}
fn main() {
    let bytes = vec![0x41, 0x42, 0x43, 0x0D, 0x0A, 0x41, 0x42, 0x43];
    let s = String::from_utf8(bytes).expect("Found invalid UTF-8");
    
    println!("one: {}", s.clone());
    
    let x = A {
        des: s
    };
    
    println!("two: {:?}", x);
}

one: ABC
ABC
two: A { des: "ABC\r\nABC" }

why result "one" and "two" "\r\n" have different behavior? if i want result two have the same behavior as one, how?

This is just the difference between Debug and Display for String/&str.

fn main() {
    let s = "ABC\n123";
    println!("{s}");
    println!("{s:?}");
}
ABC
123
"ABC\n123"

Do you want newlines in the Debug impl for A, or do you want to implement Display for A?

I want newlines in the Debug impl for A .

You can make a custom impl that uses Display for the string:

struct A {
    des: String,
}

use std::fmt;
impl fmt::Debug for A {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("A")
            .field("des", &format_args!("{}", self.des))
            .finish()
    }
}

(rust-analyzer is helpful for making custom Debug impls)

2 Likes