How to handle indentation in Display?

Hi experts, here is my code

#[derive(Debug)]
struct A {
    x: f64,
    y: f64,
    unit: String,
}
impl Default for A {
    fn default() -> Self {
        A {
            x: 0.0,
            y: 0.0,
            unit: String::from("m"),
        }
    }
}
impl std::fmt::Display for A {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "A {{\n")?;
        write!(f, "    x: {} {},\n", self.x, self.unit)?;
        write!(f, "    y: {} {},\n", self.y, self.unit)?;
        write!(f, "}}")
    }
}

#[derive(Debug)]
struct B {
    items: std::vec::Vec<A>,
}
impl std::fmt::Display for B {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "B {{\n")?;
        write!(f, "    items: [\n")?;
        for item in self.items.iter() {
            write!(f, "        {},\n", item)?;
        }
        write!(f, "    ],\n")?;
        write!(f, "}}")
    }
}


fn main() {
    let data = B {
        items: vec![A::default()],
    };
    println!("{}", data);
    println!("{:#?}", data);
}

The output is

B {
    items: [
        A {
    x: 0 m,
    y: 0 m,
},
    ],
}
B {
    items: [
        A {
            x: 0.0,
            y: 0.0,
            unit: "m",
        },
    ],
}

You see, my Display does not handle the indentation properly. How can I get the results similar to println!("{:#?}", data)?

Thanks in advance.

I think this standard library struct should help with a lot of these tedious details.

1 Like

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.