Skip to content

Invalid type inference with Fn and Closures #46742

Closed
@oberien

Description

@oberien

The following code compiles just fine:

fn main() {
    let _: i32 = (match "" {
        "+" => ::std::ops::Add::add,
        "-" => ::std::ops::Sub::sub,
        "<" => |a,b| (a < b) as i32,
        _ => unimplemented!(),
    })(5, 5);
}

If we comment out the Sub-line, a compilation error is thrown:

error[E0308]: match arms have incompatible types
 --> src/main.rs:2:18
  |
2 |       let _: i32 = (match "+" {
  |  __________________^
3 | |         "+" => ::std::ops::Add::add,
4 | |         //"-" => ::std::ops::Sub::sub,
5 | |         "<" => |a,b| (a < b) as i32,
6 | |         _ => unimplemented!(),
7 | |     })(5, 5);
  | |______^ expected fn item, found closure
  |
  = note: expected type `fn(_, _) -> <_ as std::ops::Add<_>>::Output {<_ as std::ops::Add<_>>::add}`
             found type `[closure@src/main.rs:5:16: 5:36]`
note: match arm with an incompatible type
 --> src/main.rs:5:16
  |
5 |         "<" => |a,b| (a < b) as i32,
  |                ^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

I previously submitted this issue in #34511 (comment) , but @cramertj pointed out that this is not related to impl Trait. He also modified the example to the above code. Thus, I create this issue to move the discusson away from the impl Trait tracking issue.

/cc @eddyb @nikomatsakis

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)C-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