Skip to content

Improve error message when coercing closures fails #72457

@ldm0

Description

@ldm0
Contributor

After #71599, coercing (FnDef | Closure) x (FnDef | Closure) is possible. It fails when one of them is capturing closure. But currently the error message is not that good.
For example:

fn main() {
    // Good
    let _: fn(usize) -> usize = match true {
        true => |a| a + 1,
        false => |a| a - 1,
    };

    // Bad
    let b = 2;
    let _: fn(usize) -> usize = match true {
        true => |a| a + 1,
        false => |a| a - b,
    };
}

Emits:

error[E0308]: `match` arms have incompatible types
  --> src\main.rs:12:18
   |
10 |       let _: fn(usize) -> usize = match true {
   |  _________________________________-
11 | |         true => |a| a + 1,
   | |                 --------- this is found to be of type `fn(usize) -> usize`
12 | |         false => |a| a - b,
   | |                  ^^^^^^^^^ expected fn pointer, found closure
13 | |     };
   | |_____- `match` arms have incompatible types
   |
   = note: expected fn pointer `fn(usize) -> usize`
                 found closure `[closure@src\main.rs:12:18: 12:27 b:_]`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

We actually can hint user to use non-capturing closure here.
This is related to #71895

Activity

changed the title [-]Improve error message when coercing closures failed.[/-] [+]Improve error message when coercing closures fails[/+] on May 22, 2020
added
A-diagnosticsArea: Messages for errors, warnings, and lints
T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
on May 22, 2020
added
A-closuresArea: Closures (`|…| { … }`)
A-coercionsArea: implicit and explicit `expr as Type` coercions
C-enhancementCategory: An issue proposing an enhancement or a PR with one.
on May 22, 2020
arora-aman

arora-aman commented on Nov 6, 2020

@arora-aman
Member

@rustbot claim

added a commit that references this issue on Jan 13, 2021
45ba015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

A-closuresArea: Closures (`|…| { … }`)A-coercionsArea: implicit and explicit `expr as Type` coercionsA-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.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

    Participants

    @jonas-schievink@arora-aman@ldm0@LeSeulArtichaut

    Issue actions

      Improve error message when coercing closures fails · Issue #72457 · rust-lang/rust