简体   繁体   中英

rust - How to implement custom formatting struct

code


    #[derive(Debug)]
    struct Point {
        x: i32,
        y: i32,
    }

    #[derive(Debug)]
    struct Foo {
        point: Point
    }
    
    impl fmt::Display for Foo {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            writeln!(f, "({:#?})", self)
        }
    }
    
    const origin: Point = Point { x: 0, y: 0 };
    const foo: Foo = Foo { point: origin};
    println!("{}", foo);

output

Using # gives pretty output, but not what I expected.

(Foo {
    point: Point {
        x: 0,
        y: 0,
    },
})

expected result

I want to output the result like below. How should I implement it?

Foo {
  point: Point {x: 0, y: 0}
}

There are multiple ways you could implement it, the easiest I see is adding a fmt::Display for Point . And being explicit in Foo . Like,

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            r#"Foo {{
    point: {}
}}"#,
            self.point
        )
    }
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Point {{ x: {}, y: {} }}", self.x, self.y)
    }
}

I then get

Foo {
    point: Point { x: 0, y: 0 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM