2

I have two traits, TypeOne and TypeTwo describing different kinds of objects. Both implement Sized so they are not object-safe (I cannot implement for dyn TypeOne or dyn TypeTwo). I also have a third trait Hashable which I would like to implement for both TypeOne and TypeTwo.

pub trait Hashable {
    fn hash(&self) -> &str;
}

pub trait TypeOne { }

pub trait TypeTwo { }

impl<T: TypeOne> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}

impl<T: TypeTwo> Hashable for T {
    fn hash(&self) -> &str {
        todo!();
    }
}

The above code gives a conflicting implementations error, which I fully understand. If a struct were to implement both TypeOne and TypeTwo it would have two different (i.e. conflicting) implementations.

From my understanding after asking a related question, there is a way to circumvent this limitation when the traits are defined within the same crate (see @kmdreko's response). Does anyone know a way around this?

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • I don't think there is a way. – Chayim Friedman Jan 04 '23 at 18:40
  • 1
    Does this answer your question? [Pick preferred implementation on conflicting trait implementation (using negative bounds)](https://stackoverflow.com/questions/65131776/pick-preferred-implementation-on-conflicting-trait-implementation-using-negativ) – Ahmed Masud Jan 04 '23 at 19:04
  • 2
    It only works in the related question because the `BIG` implementation is with a concrete type that is known to not conflict. That does not extend to implementing the trait on a generic type. Generics are not constrained to types only within your crate. – kmdreko Jan 04 '23 at 19:21
  • Are you just trying to do a dynamic dispatch based on a choice of "algorithm" for hash ? – Ahmed Masud Jan 04 '23 at 19:28
  • @AhmedMasud I'm not sure negative bounds will work because in that example they are implementing negative bounds on a concrete type u32 instead of trait but I will play around with it a little more. – gormatron3000 Jan 04 '23 at 19:35
  • @AhmedMasud previously I had "trait TypeOne: Hashable" but each concrete instantiation of these traits has the same hash function using internal methods of the trait (not shown for simplicity). I was hoping there was a way to generically implement this rather than requiring concrete implementations. – gormatron3000 Jan 04 '23 at 19:35
  • @gormatron3000 yeah that doesn't work :'( — because without the concrete type the compiler has lost the information about which one to select. – Ahmed Masud Jan 04 '23 at 19:42

0 Answers0