Skip to content

Improve error message when coercing closures fails #72457

Closed
@ldm0

Description

@ldm0

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

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

No branches or pull requests

Issue actions