Generic traits, conflicting implementations

⚓ Rust    📅 2025-11-02    👤 surdeus    👁️ 3      

surdeus

Hello everyone :grinning_face:

I have two scenarios with generics that give me conflicting implementation, where no conflicts are really present. What I'm misunderstanding? Is the compiler simply too much conservative?

  1. Simple trait and generic type. In the first case I implement GenericTrait on SomeStruct<T> where the two T in the impls are disjoint sets and so also the two SomeStruct<T> are disjoint sets (even better, no type implements both TraitA and TraitB). I can't see any conflicting implmenetation.
// traits

trait GenericTrait {}
trait TraitA {}
trait TraitB {}

// impls

struct SomeStruct<T> {
    val: T,
}

impl<T> GenericTrait for SomeStruct<T> where T: TraitA {}
impl<T> GenericTrait for SomeStruct<T> where T: TraitB {}

// error[E0119]: conflicting implementations of trait `GenericTrait` for type `SomeStruct<_>`
// --> src/chapters/test.rs:26:1
// |
// 25 | impl<T> GenericTrait for SomeStruct<T> where T: TraitA {}
// | ------------------------------------------------------ first implementation here
// 26 | impl<T> GenericTrait for SomeStruct<T> where T: TraitB {}
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `SomeStruct<_>`
//
// For more information about this error, try `rustc --explain E0119`.
// error: could not compile `rust-handbook` (lib) due to 1 previous error
  1. Generic trait and simple type. The second case uses generic traits. The scenario is different, but it's clear that the two T in the GenericTratit<T> impls are disjoint sets, so I can't see any conflict.

// traits
trait GenericTrait<T> {}
trait TraitA {}
trait TraitB {}

// impls

struct SomeStruct {}

impl<T> GenericTrait<T> for SomeStruct where T: TraitA {}
impl<T> GenericTrait<T> for SomeStruct where T: TraitB {}

// error[E0119]: conflicting implementations of trait `GenericTrait<_>` for type `SomeStruct`
// --> src/chapters/test.rs:11:1
// |
// 10 | impl<T> GenericTrait<T> for SomeStruct where T: TraitA {}
// | ------------------------------------------------------ first implementation here
// 11 | impl<T> GenericTrait<T> for SomeStruct where T: TraitB {}
// | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `SomeStruct`
//
// For more information about this error, try `rustc --explain E0119`.
// error: could not compile `rust-handbook` (lib) due to 1 previous error

Thanks for the help!

5 posts - 3 participants

Read full topic

🏷️ Rust_feed