Skip to content

Improve output of impl Trait errors #68110

Closed
@estebank

Description

@estebank

Given the following code:

struct S;
struct Y;

trait Trait {}

impl Trait for S {}
impl Trait for Y {}

fn foo() -> impl Trait {
    if true {
        return S;
    }
    Y
}

fn bar() -> impl Trait {
    unimplemented!()
}

we currently emit:

error[E0308]: mismatched types
  --> src/main.rs:13:5
   |
9  | fn foo() -> impl Trait {
   |             ---------- expected because this return type...
10 |     if true {
11 |         return S;
   |                - ...is found to be `S` here
12 |     }
13 |     Y
   |     ^ expected struct `S`, found struct `Y`
   |
   = note: expected type `S`
              found type `Y`

error[E0277]: the trait bound `(): Trait` is not satisfied
  --> src/main.rs:16:13
   |
16 | fn bar() -> impl Trait {
   |             ^^^^^^^^^^ the trait `Trait` is not implemented for `()`
   |
   = note: the return type of a function must have a statically known size

The first case should suggest boxing everything instead of using impl Trait:

fn foo() -> Box<dyn Trait> {
    if true {
        return Box::new(S);
    }
    Box::new(Y)
}

The second case should point at the source of the (): Trait bound:

error[E0277]: the trait bound `(): Trait` is not satisfied
  --> src/main.rs:16:13
   |
16 | fn bar() -> impl Trait {
   |             ^^^^^^^^^^ the trait `Trait` is not implemented for `()`
17 |     unreachable!()
   |     -------------- this doesn't implement trait `Trait`

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-impl-traitArea: `impl Trait`. Universally / existentially quantified anonymous types with static dispatch.A-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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