s4eed
s4eed

Reputation: 7891

Re-implement Debug trait for a third-party struct in Rust

I have an autogenerated struct named Address by protobuf in Rust. It has a predefined Debug trait like this:

impl ::std::fmt::Debug for Address {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        ::protobuf::text_format::fmt(self, f)
    }
}

But I want to customize how it's printed when {:#?} is used. So I decided to implement Debug trait for it like this in my project:

impl fmt::Debug for EvmProto::Address {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
      ....
    }
}

But it complains that conflicting implementations of trait `std::fmt::Debug` for type `protos::Evm::Address

Upvotes: 1

Views: 1202

Answers (1)

denis.peplin
denis.peplin

Reputation: 9851

UPDATE: while the answer can still be useful in some similar cases, in this case it seems incorrect. See the comments for details.

You can't implement an external trait on an external type.

I'm citing The Rust Book

we can’t implement external traits on external types. For example, we can’t implement the Display trait on Vec<T> within our aggregator crate, because Display and Vec<T> are both defined in the standard library and aren’t local to our aggregator crate. This restriction is part of a property called coherence, and more specifically the orphan rule, so named because the parent type is not present. This rule ensures that other people’s code can’t break your code and vice versa. Without the rule, two crates could implement the same trait for the same type, and Rust wouldn’t know which implementation to use.

Upvotes: 2

Related Questions