display_tree icon indicating copy to clipboard operation
display_tree copied to clipboard

Allow deriving `DisplayTree` for unconostrained generic parameters

Open FireFragment opened this issue 1 year ago • 0 comments

The following code fails to build:

#[derive(DisplayTree)]
struct Hello<T> {
    field: T,
}

The error message:

error[E0277]: `T` doesn't implement `std::fmt::Display`
  --> common/src/lib.rs:27:10
   |
27 | #[derive(DisplayTree)]
   |          ^^^^^^^^^^^ `T` cannot be formatted with the default formatter
28 | struct Hello<T> {
29 |     field: T,
   |     ----- in this macro invocation
   |
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: this error originates in the macro `$crate::__export::format_args` which comes from the expansion of the macro `::std::format` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider restricting type parameter `T`
   |
28 | struct Hello<T: std::fmt::Display> {
   |               +++++++++++++++++++

For more information about this error, try `rustc --explain E0277`.

It would be nice, if the proc macro in this case generated valid implementation too, by constraining T to be fmt::Display in the implementation, something along the lines of:

impl<T: std::fmt::Display> DisplayTree for Hello<T> {
    // ... implementation ...
}

This can be useful, when one wants to be able to display the tree when possible, but doesn't want to needlessly introduce the T: fmt::Display bound on the struct itself. Standard library traits like Clone or Debug work like this.

FireFragment avatar Aug 01 '24 17:08 FireFragment