Newline escape character behavior different

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
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";

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 {
            .field("des", &format_args!("{}", self.des))

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


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.