Conflicting implementations in the standard library


#1

Hi all,

I am new here and new to Rust in general. So far, some of it is simply brilliant.
Other things, I still don’t fully understand.

Let’s start with my most recent issue:

use std::fmt;
use std::string;

struct Abc {}

impl string::ToString for Abc {
    
}

impl fmt::Display for Abc {
    
}

fn main() {
    println!("Hello World!");
}

I have to admit, I don’t fully understand the module system in general either: it’s not as plain simple as in C, nor as “intelligent” as Python’s or Node’s. Still, it’s something I can get used to.

However, in this case, I suspect std::fmt “imports” the collections crate, which subsequently redefines string::ToString. Bottom line is that this very simple file yields the following error:

error[E0119]: conflicting implementations of trait `std::string::ToString` for type `Abc`:
 --> test.rs:6:1
  |
6 |   impl string::ToString for Abc {
  |  _^ starting here...
7 | | }
  | |_^ ...ending here
  |
  = note: conflicting implementation in crate `collections`

Usually, the errors that the rust compiler spits out are fairly eloquent. This time, however, it confuses me. I know that it is possible for modules to “export” other modules (by using pub use). However, why would it complain about conflicting implementations? If I remove use std::fmt and the Display trait implementation, it does work.

Anyway, hopefully you can explain to me why it does this so I can get a better understanding of the module system as a whole!

Greetings,

Tim


#2

According to the docs:

This trait is automatically implemented for any type which implements the Display trait. As such, ToString shouldn’t be implemented directly


#3

And on that same docs page, this is shown under “Implementors”:

impl<T> ToString for T
  where T: Display + ?Sized

#4

Thanks a lot! This makes perfect sense now. @cuviper really incredible that that’s possible.