Skip to content

Returning a comparison expression with a match fails depending on the operand order #47287

Closed
@NPN

Description

@NPN

Suppose the return expression of a function is a comparison between a match expression and some other operand. If the operand and comparison operator come before the match expression, the code compiles. However, if the operand and comparison operator come after the match expression, the code fails to compile.

fn works(x: u32) -> bool {
    0 < match x {
        _ => 1,
    }
}

fn fails(x: u32) -> bool {
    match x {
        _ => 1,
    } > 0
}

The error is thus:

error: expected expression, found `>`
  --> src/main.rs:10:7
   |
10 |     } > 0
   |       ^

error[E0308]: match arms have incompatible types
  --> src/main.rs:8:5
   |
8  | /     match x {
9  | |         _ => 1,
10 | |     } > 0
   | |_____^ expected bool, found integral variable
   |
   = note: expected type `bool`
              found type `{integer}`
note: match arm with an incompatible type
  --> src/main.rs:9:14
   |
9  |         _ => 1,
   |              ^

Strangely, the code does work if the comparison is a statement:

fn wontfail(x: u32) -> bool {
    let y = match x {
        _ => 1,
    } > 0;
    y
}

Tested using rustc 1.23.0 on Playground.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-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