Implement a trait for multiple generic traits

I'm trying to implement a trait for Display and Debug traits, but rust responds with conflicting implementations.

Here is my code:

pub trait AsString {
    fn as_string(self) -> String;
}

impl<T: Display> AsString for T {
    fn as_string(self) -> String {
        self.to_string()
    }
}

impl<T: Debug> AsString for T {
    fn as_string(self) -> String {
        format!("{:?}", self)
    }
}

But rust gives me:

error[E0119]: conflicting implementations of trait `AsString`
  --> src/convert_test_result.rs:43:1
   |
37 | impl<T: Display> AsString for T {
   | ------------------------------- first implementation here
...
43 | impl<T: Debug> AsString for T {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

How can I solve the issue?

You need specialization (not coming any time soon) to really solve the issue.[1]

You can choose to keep one of the blanket implementations and implement it for other things non-generically (or generic on their parameters, not their "outer types").

You can supply a generic newtype or types that implements the trait generically on the wrapped type (for example).


  1. E.g. what should &str do? It implements both Display and Debug and the implementations do different things. ↩ī¸Ž

1 Like

Thanks for your response, I need to find another approach to my problem then...