Error: the method exists but the following trait bounds were not satisfied

Hi, I have the following program:

use std::marker::PhantomData;

trait A {}
trait B: A {}

impl A for i32 {}
impl B for i32 {}

impl A for bool {}

trait K<T: A> {
    fn w(&self);
}

struct Foo<T: A> {
    _marker: PhantomData<T>,
}
impl<T: B> K<T> for Foo<T> {
    fn w(&self) {}
}
impl K<bool> for Foo<bool> {
    fn w(&self) {}
}

struct Bar<T: A> {
    foo: Foo<T>,
}

impl<T: A> Bar<T> {
    fn new() -> Self {
        let foo = Foo::<T> {
            _marker: PhantomData,
        };
        foo.w();
        Bar { foo: foo }
    }
}

which gives this error:

   |
15 | struct Foo<T: A> {
   | ---------------- method `w` not found for this
...
34 |         foo.w();
   |             ^
   |
   = note: the method `w` exists but the following trait bounds were not satisfied:
           `Foo<T> : K<_>`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `w`, perhaps you need to implement it:
           candidate #1: `K`

To me, it seems that this is valid since all the known subtypes of A have implemented the method w, but it still failed. Is that because potentially someone could implement A for another type and thus make this invalid?

I also tried to create another trait C that inherits A and implement C for bool:

use std::marker::PhantomData;

trait A {}
trait B: A {}
trait C: A {}

impl A for i32 {}
impl B for i32 {}

impl A for bool {}
impl C for bool {}

trait K<T: A> {
    fn w(&self);
}

struct Foo<T: A> {
    _marker: PhantomData<T>,
}
impl<T: B> K<T> for Foo<T> {
    fn w(&self) {}
}
impl<T: C> K<T> for Foo<T> {
    fn w(&self) {}
}

struct Bar<T: A> {
    foo: Foo<T>,
}

impl<T: A> Bar<T> {
    fn new() -> Self {
        let foo = Foo::<T> {
            _marker: PhantomData,
        };
        foo.w();
        Bar { foo: foo }
    }
}

For the second, I got:

   |
20 | impl<T: B> K<T> for Foo<T> {
   | -------------------------- first implementation here
...
23 | impl<T: C> K<T> for Foo<T> {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Foo<_>`

Generally, I’m curious if there’s any neat solution to solve this problem, i.e., implementing different behaviors for different sub-traits of a parent trait.

Thanks!

It’s invalid because in generics, Rust only lets you use traits that the generic types have been specifically constrained to, or which are implemented for all possible types the generic could be instantiated with.

If you want to use K, constrain T: A + K.

First of all, Rust doesn’t have “parent” and “child” traits. trait B: A doesn’t mean B “inherits” from A, it means "to implement B you must also implement A".

Secondly, to do this you need specialization, which isn’t in the language yet. Until it is, you can’t have overlapping implementations like this.