Skip to content

Type inference failure leads to incorrect "match arm with an incompatible type" message #57206

Closed
@mqudsi

Description

@mqudsi

In the code sample below, there are two ultimately identical functions with the same problem, but while the compiler correctly reports the incorrect match block in the first function (test_func1()), it fails to do so in the second (test_func2()):

fn main() {
    let _ = test_func1(1);
    let _ = test_func2(1);
}

fn test_func1(n: i32) -> i32 {
    match n {
        12 => 'b',
        _ => 42,
    }
}

fn test_func2(n: i32) -> i32 {
    let x = match n {
        12 => 'b',
        _ => 42,
    };

    x
}

which produces the following correct error for the first function:

error[E0308]: match arms have incompatible types
  --> ./test.rs:7:5
   |
7  | /     match n {
8  | |         12 => 'b',
   | |               --- match arm with an incompatible type
9  | |         _ => 42,
10 | |     }
   | |_____^ expected i32, found char

but an incorrect error for the second message:

error[E0308]: match arms have incompatible types
  --> ./test.rs:14:13
   |
14 |       let x = match n {
   |  _____________^
15 | |         12 => 'b',
16 | |         _ => 42,
   | |              -- match arm with an incompatible type
17 | |     };
   | |_____^ expected char, found integral variable
   |
   = note: expected type `char`
              found type `{integer}`

When test_func2() is extended with an explicit type hint (that should not be necessary as it can be derived from the existing code), the resulting error message is correct once again:

fn test_func3(n: i32) -> i32 {
    let x: i32 = match n {
        12 => 'b',
        _ => 42,
    };

    x
}

producing

error[E0308]: match arms have incompatible types
  --> ./test.rs:23:18
   |
23 |       let x: i32 = match n {
   |  __________________^
24 | |         12 => 'b',
   | |               --- match arm with an incompatible type
25 | |         _ => 42,
26 | |     };
   | |_____^ expected i32, found char

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-inferenceArea: Type inference

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions