Skip to content

Matching on usize requires half-open range #146476

@mkeeter

Description

@mkeeter

usize ranges in match statements are surprising:

fn test(i: usize) {
    match i {
        0..=usize::MAX => todo!(),
    }
}

I expected this to compile; instead, rustc returns an error:

error[E0004]: non-exhaustive patterns: `usize::MAX..` not covered
 --> src/lib.rs:2:11
  |
2 |     match i {
  |           ^ pattern `usize::MAX..` not covered
  |
  = note: the matched value is of type `usize`
  = note: `usize` does not have a fixed maximum value, so half-open ranges are necessary to match exhaustively
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
3 ~         0..=usize::MAX => todo!(),
4 ~         usize::MAX.. => todo!(),
  |

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

This is obviously a known edge case, given the custom error message (which is great!), but it's still a weird paper cut. It's especially weird to declare "usize does not have a fixed maximum value" when usize::MAX is right there!

Doing a little digging, it looks like it dates back to at least #118598

Meta

rustc --version --verbose:

rustc 1.89.0 (29483883e 2025-08-04)
binary: rustc
commit-hash: 29483883eed69d5fb4db01964cdf2af4d86e9cb2
commit-date: 2025-08-04
host: aarch64-apple-darwin
release: 1.89.0
LLVM version: 20.1.7

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-exhaustiveness-checkingRelating to exhaustiveness / usefulness checking of patternsA-patternsRelating to patterns and pattern matchingC-bugCategory: This is a bug.E-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions