Confusing type checker diagnose

āš“ Rust    šŸ“… 2025-07-30    šŸ‘¤ surdeus    šŸ‘ļø 10      

surdeus

Warning

This post was published 126 days ago. The information described in this article may have changed.

I’m sorry for the ambiguous title, but I cannot find a proper word to describe the pattern of this bug.

The code is:

trait WithGeneric<T> {
    type Assoc;
}

trait Foo {
    type Assoc;

    fn foo<P>(p: &mut P)
    where
        P: WithGeneric<Self::Assoc>,
        P::Assoc: Foo;
}

struct Bar<F> {
    phantom: std::marker::PhantomData<F>,
}

impl<F: Foo> Foo for Bar<F> {
    type Assoc = F;
    
    fn foo<P>(p: &mut P)
    where
        P: WithGeneric<F>,
        P::Assoc: Foo {}
}

The compiler output is (see this playground):

error[E0277]: the trait bound `P: WithGeneric<F>` is not satisfied
  --> src/lib.rs:21:5
   |
21 | /     fn foo<P>(p: &mut P)
22 | |     where
23 | |         P: WithGeneric<F>,
24 | |         P::Assoc: Foo {}
   | |_____________________^ the trait `WithGeneric<F>` is not implemented for `P`

error[E0276]: impl has stricter requirements than trait
  --> src/lib.rs:23:12
   |
8  | /     fn foo<P>(p: &mut P)
9  | |     where
10 | |         P: WithGeneric<Self::Assoc>,
11 | |         P::Assoc: Foo;
   | |______________________- definition of `foo` from trait
...
23 |           P: WithGeneric<F>,
   |              ^^^^^^^^^^^^^^ impl has extra requirement `P: WithGeneric<F>`

Hmmmmmm, it's conflict with itself.

So clearly, the diagnose text is wrong. Moreover, I wonder why this code cannot compile.

2 posts - 2 participants

Read full topic

šŸ·ļø Rust_feed