Rust fmt::Display blanket implementation

See the playground example here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a9af4ed55c529c52ad3b9c2f8608db7c

I want to provide a fmt::Display implementation for all traits that implement my own custom trait but it fails with the errors below. Is there any other way for me to work-around this without having to manually implement fmt::Display for all structs that implement Foo?

error[E0119]: conflicting implementations of trait `std::fmt::Display` for type `&_`:
 --> src/lib.rs:5:1
  |
5 | impl <T: Foo + Sized> std::fmt::Display for T {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: conflicting implementation in crate `core`:
          - impl<T> std::fmt::Display for &T
            where T: std::fmt::Display, T: ?Sized;
  = note: downstream crates may implement trait `Foo` for type `&_`
error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> src/lib.rs:5:7
  |
5 | impl <T: Foo + Sized> std::fmt::Display for T {
  |       ^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: implementing a foreign trait is only possible if at least one of the types for which is it implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter
error: aborting due to 2 previous errors
1 Like

No, because some downstream crate could implement both your trait and Diplay, so Rust will reject your blanket impl. What you can do is provide a tiny wrapper type that implements display if your trait is implemented.

pub struct ShowFoo<F>(pub F);

impl<F: Foo> Display for ShowFoo<F> {
    ...
}

If you go this route, it will be helpful if you also provide the blanket impl

impl<F: Foo + ?Sized> Foo for &F { ... }

That way if you can do something like

println!("{}", ShowFoo(&my_foo))

and not have to transfer ownership of my_foo

1 Like

That will work but I was hoping for a solution without having to wrap the type. I am guessing that solution does not exist?

1 Like

The only other option is writing a Display impl for all of your types. You could use a macro to make this easier.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.