[Solved] Match on u8, '0' to '9'

#1
  1. I am matching on a u8, I have something like:
let x: u8 = ...
match x {
... other matches ...

                    b'0' | b'1' | b'2' | b'3' | b'4' | b'5' | b'6' | b'7' | b'8' | b'9' =>  {
...

                    }
... other matches...
}

Is there a better way to write this than enumerating the 0 -> 9?

#2
match x {
    b'0' ..= b'9' => {
        // ...
    }
    // ...
}
3 Likes
#3

@mbrubeck Presents a nice solution, although if you want a specific set of non-consecutive numbers (IE "abc123ABC") then something like the following will work as well:

match x {
    x if b"abc123ABC".contains(&x) => {
        //...
    }
    //...
}
1 Like
#4

I mean, at that point, you’re not really using match. An actual pattern list is more likely to optimise well:

match x { b'a'..=b'c' | b'1'..=b'3' | b'A'..=b'C' => ... }
2 Likes
#5

I like both solutions, for ..= and TIL you can embed an ‘if’ into a match statement.