Skip to content

Failure to unify concrete type with associated type #70030

@joshlf

Description

@joshlf

I tried this code:

trait Refable<'a> {
    type Ref;
}

impl<'a, R: 'a> Refable<'a> for R {
    type Ref = &'a R;
}

trait GetRef<F> {
    fn get_ref<'a>(&'a self) -> <F as Refable<'a>>::Ref
    where
        F: 'a + Refable<'a>;
}

struct Foo;

struct Bar {
    foo: Foo,
}

impl<R: GetRef<Bar>> GetRef<Foo> for R {
    fn get_ref<'a>(&'a self) -> <Foo as Refable<'a>>::Ref
    where
        Foo: 'a + Refable<'a>,
    {
        // Doesn't compile
        &self.get_ref().foo

        // Compiles
        // fn get<'a>(r: <Bar as Refable<'a>>::Ref) -> <Foo as Refable<'a>>::Ref {
        //     &r.foo
        // }
        // get(self.get_ref())
    }
}

I expected to see this happen: It compiles properly

Instead, this happened: It fails with the following error:

error[E0308]: mismatched types
  --> src/lib.rs:27:9
   |
22 |     fn get_ref<'a>(&'a self) -> <Foo as Refable<'a>>::Ref
   |                                 ------------------------- expected `<Foo as Refable<'a>>::Ref` because of return type
...
27 |         &self.get_ref().foo
   |         ^^^^^^^^^^^^^^^^^^^ expected associated type, found `&Foo`
   |
   = note: expected associated type `<Foo as Refable<'a>>::Ref`
                    found reference `&Foo`
   = note: consider constraining the associated type `<Foo as Refable<'a>>::Ref` to `&Foo` or calling a method that returns `<Foo as Refable<'a>>::Ref`
   = note: for more information, visit https://doc.rust-lang.org/book/ch19-03-advanced-traits.html

However, if I un-comment the code labeled "Compiles" above, which simply wraps the same expression in a bare function, it compiles successfully.

Meta

Version: 1.42.0 Stable (Playground)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-coercionsArea: implicit and explicit `expr as Type` coercionsC-bugCategory: This is a bug.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