Skip to content

Incorrect suggestion when trying to implement Trait<Associated = ()> with impl Trait + 'static #87261

Description

@patrick-gu

Given the following code (Playground):

trait Trait {
    type Associated;
}

fn returns_opaque() -> impl Trait + 'static {
    struct Impl;

    impl Trait for Impl {
        type Associated = ();
    }

    Impl
}

fn accepts_trait<T>(_: T)
where
    T: Trait<Associated = ()>,
{
}

fn main() {
    accepts_trait(returns_opaque());
}

The current output is:

   Compiling playground v0.0.1 (/playground)
error[E0271]: type mismatch resolving `<impl Trait as Trait>::Associated == ()`
  --> src/main.rs:22:5
   |
5  | fn returns_opaque() -> impl Trait + 'static {
   |                        -------------------- the found opaque type
...
15 | fn accepts_trait<T>(_: T)
   |    ------------- required by a bound in this
16 | where
17 |     T: Trait<Associated = ()>,
   |              --------------- required by this bound in `accepts_trait`
...
22 |     accepts_trait(returns_opaque());
   |     ^^^^^^^^^^^^^ expected `()`, found associated type
   |
   = note:    expected unit type `()`
           found associated type `<impl Trait as Trait>::Associated`
help: consider constraining the associated type `<impl Trait as Trait>::Associated` to `()`
   |
5  | fn returns_opaque() -> impl Trait + 'static<Associated = ()> {
   |                                            ^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0271`.
error: could not compile `playground`

To learn more, run the command again with --verbose.

The syntax impl Trait + 'static<Associated = ()> does not actually work.

Ideally the suggested fix should look like:

help: consider constraining the associated type `<impl Trait as Trait>::Associated` to `()`
   |
5  | fn returns_opaque() -> impl Trait<Associated = ()> + 'static {
   |                                  ^^^^^^^^^^^^^^^^^

This bug appears to be present in stable, beta, and nightly, on both Rust 2015 and 2018.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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