0

If I try to compile this code:

fn main() {
    let a = 0;
    let (fun, i) = match a {
        0 => (fun1, 1), _ => (fun2, 2),
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}

I get the following error:

error[E0308]: `match` arms have incompatible types
 --> src/main.rs:4:30
  |
3 |       let (fun, i) = match a {
  |  ____________________-
4 | |         0 => (fun1, 1), _ => (fun2, 2),
  | |              ---------       ^^^^^^^^^ expected fn item, found a different fn item
  | |              |
  | |              this is found to be of type `(fn(i32) -> i32 {fun1}, {integer})`
5 | |     };
  | |_____- `match` arms have incompatible types
  |
  = note: expected tuple `(fn(_) -> _ {fun1}, {integer})`
             found tuple `(fn(_) -> _ {fun2}, {integer})`

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

However, this functionally equivalent but less concise version:

fn main() {
    let a = 0;
    let fun = match a {
        0 => fun1, _ => fun2,
    };
    let i = match a {
        0 => 1, _ => 2,
    };
    fun(i);
}

fn fun1(a: i32) -> i32 {
    a
}

fn fun2(a: i32) -> i32 {
    a
}

Compiles and runs fine.

Why is this? Is it possible to make the first version work with some type hint, or somehow else?

jdehesa
  • 58,456
  • 7
  • 77
  • 121

0 Answers0