1

I have some local types, say

struct A;
struct B;

which all implement a local trait MyTrait:

pub trait MyTrait { }

impl MyTrait for A { }
impl MyTrait for B { }

Now I want to implement a standard library trait for both A and B, generically:

impl<T: MyTrait> ToString for T {
    fn to_string(&self) -> String {
        todo!()
    }
}

However, due to the orphan rule, this is not allowed:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> src/main.rs:9:6
  |
9 | impl<T: MyTrait> ToString 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 it is implemented is local
  = note: only traits defined in the current crate can be implemented for a type parameter

Is there a way to make this work (except macros) and if so, how? It need to implement the trait for these specific types, not some wrapper type.

Einliterflasche
  • 473
  • 6
  • 18
  • 3
    Rust doesn't allow this. There could be a type `Foo` that already implements `ToString`. If it tries to implement `MyTrait`, then implementations would conflict. You'll have to add the `ToString` implementation for each type manually. BTW, you should usually implement `Display` instead of `ToString`. – PitaJ Jul 18 '23 at 15:59
  • There is a proposal for a feature called "sealed traits", which would enforce that a local trait as you call it can only be implemented in the current trait, that would allow what you are asking for. – jthulhu Jul 18 '23 at 16:58
  • 1
    I already love rust, but sometimes I wish it was 10 years from now and I could use rust without occasionally bumping into some incomplete feature – Einliterflasche Jul 18 '23 at 17:36
  • @jthulhu If I recall correctly, the current proposal for sealed traits does not make (and disallows) these coherency modifications, but it talks about the possibility that some future proposal will add a different mechanism for sealed traits that will affect coherency. – Chayim Friedman Jul 18 '23 at 18:24
  • @Einliterflasche No programming languages covers 100% of the use cases with 100% convenience. Just accept it (and in this case, use a macro). It doesn't mean the language or its features are incomplete (there are some features that I can accept being called incomplete, but I don't think coherency is one of them). – Chayim Friedman Jul 18 '23 at 18:26
  • @Einliterflasche on the other hand, that makes you living in a very exciting time! – jthulhu Jul 18 '23 at 18:39

0 Answers0