#[derive(Display("({x}, {y})"))]

While it is nice to get Debug derived, sadly the same is not true for the similar Display. Now obviously there is no canonical right implementation, but often only the inner part of five lines varies. So I propose this:

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

which would generate this:

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

In case of a struct one could go even further, aliasing the members:

#[derive(Display("({x}, {y})"))]

While a tuple struct could maybe have a less pretty:

#[derive(Display("({_0}, {_1})"))]
4 Likes

It would be really nice if derives could receive parameters. For comparison, the equivalent derive_more code takes an extra line

#[derive(Debug, Display)]
#[display("({x}, {y})")]
struct Point {
    x: i32,
    y: i32,
}
12 Likes

How is this supposed to handle padding, alignment, and precision?

Maybe using the same syntax from format!()? Like the derive_more crate does

7 Likes

@user16251 Certainly, that’s pretty much the Rust standard! This is the syntax of format_args!(), which is the common denominator of print!(), write!(), log::warn!(), etc. My title was meant to imply that you should get all that goodness.

Another benefit of the extra line is to be able to use this on enums too, like derive_more does (#[display(...)] on each variant)

10 Likes