Skip to content

Misleading compile error message when checking match arm types. #78124

Closed
@supermank17

Description

@supermank17

I ran into a case where the compiler is complaining that match arms have incompatible types, as seen in this code snippet below.
However, the line it is pointing to is not necessarily incorrect: the real issue is that the outer "shouldwe" Some => match-arm is not returning a u32 as expected. (In other words, this can be made to compile by adding a return after the match shouldwe2 statement).
I eventually realized the actual issue, but this could possibly be clarified by pointing at the outer shouldwe match instead of the inner shouldwe2 match.

#![allow(unused)]

fn test(shouldwe: Option<u32>, shouldwe2: Option<u32>) -> u32 {
    match shouldwe {
        Some(val) => {
            match shouldwe2 {
                Some(val) => {
                    return val;
                }
                None => (),
            }
        }
        None => return 12,
    }
}

fn main() {
    println!("returned {}", test(None, Some(5)));
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0308]: `match` arms have incompatible types
  --> src/main.rs:10:25
   |
6  | /             match shouldwe2 {
7  | |                 Some(val) => {
8  | |                     return val;
   | |                     ----------- this is found to be of type `u32`
9  | |                 }
10 | |                 None => (),
   | |                         ^^ expected `u32`, found `()`
11 | |             }
   | |_____________- `match` arms have incompatible types

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.D-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.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