Skip to content

Matching a const Range #76191

Description

@Typas

When I was doing rustlings, I found out it is possible to match with a range which is coded like this:

fn color(n: i32) -> Option<u8> {
    match n {
        0..=255 => Some(n as u8),
        _ => None,
    }
}

but when I trying to replace the range with a const,

use std::ops::RangeInclusive;

const RGB_RANGE: RangeInclusive<i32> = 0..=255;

fn color(n: i32) -> Option<u8> {
    match n {
        RGB_RANGE => Some(n as u8),
        _ => None,
    }
}

the compiler gives error:

error[E0308]: mismatched types
 --> src/main.rs:7:9
  |
3 | const RGB: RangeInclusive<i32> = 0..=255;
  | ----------------------------------------- constant defined here
...
6 |     match n {
  |           - this expression has type `i32`
7 |         RGB => Some(n as u8),
  |         ^^^
  |         |
  |         expected `i32`, found struct `std::ops::RangeInclusive`
  |         `RGB` is interpreted as a constant, not a new binding
  |         help: introduce a new binding instead: `other_rgb`
  |
  = note: expected type `i32`
           found struct `std::ops::RangeInclusive<i32>`

I have no idea why matching a literal range is possible but not matching a constant which type is RangeInclusive.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-patternsRelating to patterns and pattern matchingC-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