Skip to content

Order matters when resolving supertrait #72582

Closed
@tavianator

Description

@tavianator

This code:

trait Foo: PartialOrd + PartialOrd<i32> {}

trait Bar {
    type Baz: Foo;

    fn bar(&self) -> Self::Baz;
}

fn baz<T: Bar>(x: T, y: T) -> bool {
    x.bar() < y.bar()
}

gives this error:

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/lib.rs:10:15
   |
10 |     x.bar() < y.bar()
   |               ^^^^^^^ expected `i32`, found associated type
   |
   = note:         expected type `i32`
           found associated type `<T as Bar>::Baz`
   = note: consider constraining the associated type `<T as Bar>::Baz` to `i32`
   = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html

which indicates that only the PartialOrd<i32> impl is being considered. It seems like the only way to fix it at the usage site is something like

<T::Baz as PartialOrd>::partial_cmp(&x.bar(), &y.bar())

On the other hand, just swapping the order of the supertraits fixes it:

trait Foo: PartialOrd<i32> + PartialOrd {}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-trait-systemArea: Trait systemC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.T-compilerRelevant to the compiler 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