Wrong type inference(impl where does not work)?


pub trait HashMethod {

pub struct HashMethodFixedKeys<T> {
    t: std::marker::PhantomData<T>,

pub type HashMethodKeysU8 = HashMethodFixedKeys<u8>;
pub type HashMethodKeysU16 = HashMethodFixedKeys<u16>;
pub type HashMethodKeysU32 = HashMethodFixedKeys<u32>;
pub type HashMethodKeysU64 = HashMethodFixedKeys<u64>;

impl<T> HashMethod for HashMethodFixedKeys<T> {

pub trait PolymorphicKeysHelper<Method: HashMethod> {}

trait ShortFixedKeysMarker {}

impl ShortFixedKeysMarker for HashMethodKeysU8 {}

impl ShortFixedKeysMarker for HashMethodKeysU16 {}

impl<T: ShortFixedKeysMarker + HashMethod> PolymorphicKeysHelper<T> for T {}

trait LongerFixedKeysMarker {}

impl LongerFixedKeysMarker for HashMethodKeysU32 {}

impl LongerFixedKeysMarker for HashMethodKeysU64 {}

impl<T: LongerFixedKeysMarker + HashMethod> PolymorphicKeysHelper<T> for T {

error info:

Compiling playground v0.0.1 (/playground)
error[E0119]: conflicting implementations of trait `PolymorphicKeysHelper<_>`
  --> src/lib.rs:34:1
26 | impl<T: ShortFixedKeysMarker + HashMethod> PolymorphicKeysHelper<T> for T {}
   | ------------------------------------------------------------------------- first implementation here
34 | impl<T: LongerFixedKeysMarker + HashMethod> PolymorphicKeysHelper<T> for T {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation

error: aborting due to previous error

For more information about this error, try `rustc --explain E0119`.
error: could not compile `playground`

A single type T could implement all three of ShortFixedKeysMarker, LongerFixedKeysMarker, and HashMethod, and then both of those trait impls would apply to it. This is always an error: you can't implement a trait in more than one way for a single type ("coherence"), even if the trait has no associated data.

There may be ways to work around this in your case, but to help you we'll need to know what you're trying to do in more detail.


There are two implementations of PolymerphicKeysHelper:

  • HashMethodKeysU8, HashMethodKeysU16
  • HashMethodKeysU32, HashMethodKeysU64

I don't want to have duplicate code and macros. I want to be able to implement it with generics

What does PolymorphicKeysHelper do? Does it have some associated data (types, functions, etc.) in your real code?

Until/unless #[marker] trait gets stabilized.

1 Like

That's a new one! Well, in the sense that I'd never heard of it before. The feature itself has been around for a while, apparently.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.