Associated types are ambiguous to impl coherence
⚓ Rust 📅 2025-11-19 👤 surdeus 👁️ 12Hi everyone,
Have anyone ever encountered an apparent limitation of the trait solver, where impl coherence check fails due to use of associated types?
Consider the following code:
use std::ops::{Add, Mul};
pub struct Generic<A>(A);
impl<A, B> Mul<Generic<B>> for Generic<A>
where
A: Add<B>,
{
type Output = Generic<<A as Add<B>>::Output>;
fn mul(self, rhs: Generic<B>) -> Self::Output {
Generic(self.0.add(rhs.0))
}
}
type A = <Generic<i32> as Mul<Generic<i32>>>::Output;
type B = <Generic<u32> as Mul<Generic<u32>>>::Output;
trait Trait {}
impl Trait for A {}
impl Trait for B {}
My understanding is that associated types are essentially type-level functions. They map some type to an another type. In context where all the inputs are known the output can be computed.
In the case above, both the receiver and the generic parameter of the trait are known, so the fully-qualified type alias is not ambiguous in any way, and as such compiler can determine the exact concrete type to which it resolves (Generic<i32> and Generic<u32> in the example). Yet still, this code fails to compile with rather unhelpful error message:
error[E0119]: conflicting implementations of trait `Trait` for type `<Generic<i32> as Mul>::Output`
--> src/mini.rs:23:1
|
21 | impl Trait for A {}
| ---------------- first implementation here
22 |
23 | impl Trait for B {}
| ^^^^^^^^^^^^^^^^ conflicting implementation for `<Generic<i32> as Mul>::Output`
Am I assuming something about associated type semantics that is not entirely correct here or is this a bug or some sort of limitation? I been having tough time finding any online discussion regarding that specific issue, the closest I've got was #99940, which does not match my problem description exactly.
I've been stomped by this for few weeks now and would really appreciate some help with understanding whats going on.
Edit:
I've posted a bug report on rust's repo, you can find it here.
5 posts - 4 participants
🏷️ Rust_feed