Skip to content

Trait bounds for generic types do not imply themselves when they restrict associated types #109325

Open
@Yttiricon

Description

@Yttiricon

When restricting a generic type parameter to a trait which is a super trait of another trait, and also places trait bounds on an associated type of the other trait.

For example:

trait TypeRestriction {}

trait SubTrait {
    type AssociatedType;
}

trait SuperTrait: SubTrait where Self::AssociatedType: TypeRestriction {}

fn function<T: SuperTrait>(_arg: T) {}

gives the error:

error[E0277]: the trait bound `<T as SubTrait>::AssociatedType: TypeRestriction` is not satisfied
 --> file.rs:9:16
  |
9 | fn function<T: SuperTrait>(_arg: T) {}
  |                ^^^^^^^^^^ the trait `TypeRestriction` is not implemented for `<T as SubTrait>::AssociatedType`
  |
note: required by a bound in `SuperTrait`
 --> file.rs:7:56
  |
7 | trait SuperTrait: SubTrait where Self::AssociatedType: TypeRestriction {}
  |                                                        ^^^^^^^^^^^^^^^ required by this bound in `SuperTrait`
help: consider further restricting the associated type
  |
9 | fn function<T: SuperTrait>(_arg: T) where <T as SubTrait>::AssociatedType: TypeRestriction {}
  |                                     ++++++++++++++++++++++++++++++++++++++++++++++++++++++

However, T must be able to implement Supertrait, since we asserted that it does with the trait bound T: SuperTrait.

In general, I think checking the trait bounds for trait requirements for generics (in a where clause, in <T: Trait> or (arg: impl Trait) is unnecessary, since if the trait is implemented then it shouldn't matter how, it inherently must satisfy the trait bounds, and if it does not implement the trait, then it cannot be used as that generic type, so nothing breaks.

In the example above, the function doesn't do anything at all, so any arbitrary restrictions on T should be valid, since they have no effect on the function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-trait-systemArea: Trait systemT-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions