Skip to content

Type annotations needed for type alias that refers to associated type on trait #105680

@thomaseizinger

Description

@thomaseizinger

I tried this code:

enum Foo<A> {
    A(A)
}

trait Baz {
    type A;
}

type Bar<B> = Foo<<B as Baz>::A>;

struct Impl {
    bar: Bar<Self> 
}

impl Baz for Impl {
    type A = String;    
}

fn main() {
    
    let s = Impl {
        bar: Bar::A(String::new())
    };
    
}

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=97b88d916216f04a93c1d24ca2a4f558

I expected to see this happen: It compiles without issues.

Instead, this happened:

Compiling playground v0.0.1 (/playground)
error[[E0284]](https://doc.rust-lang.org/stable/error-index.html#E0284): type annotations needed
  --> src/main.rs:22:14
   |
22 |         bar: Bar::A(String::new())
   |              ^^^ cannot infer type for type parameter `B` declared on the type alias `Bar`
   |
   = note: cannot satisfy `<_ as Baz>::A == String`

For more information about this error, try `rustc --explain E0284`.
error: could not compile `playground` due to previous error

Unless I am missing something, the type of Impl::Bar is defined unambiguously to be Foo<String>. It works once you add the type annotation:

let s = Impl {
	bar: Bar::<Impl>::A(String::new())
};

Meta

The problem is reproducible for stable, beta and nightly (tried in playground).

rustc --version --verbose:

rustc 1.65.0 (897e37553 2022-11-02)
binary: rustc
commit-hash: 897e37553bba8b42751c67658967889d11ecd120
commit-date: 2022-11-02
host: x86_64-unknown-linux-gnu
release: 1.65.0
LLVM version: 15.0.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-inferenceArea: Type inferenceA-trait-systemArea: Trait systemC-discussionCategory: Discussion or questions that doesn't represent real issues.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-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