Ok, there's a bit to unpack here.
First of all, match
isn't just using ==
. It's doing pattern matching, which allows you to do structural comparisons, or compare against multiple values.
Second, the things on the left of =>
s in a match
aren't expressions, they're patterns. Patterns look a lot like expressions, but aren't, and have different rules. In particular, '0'...'5'
is more or less just shorthand for '0' | '1' | '2' | '3' | '4' | '5'
, which means something totally different as an expression. Basically: don't conflate the two.
Third, please don't name variables after types. That's just confusing.
Fourth, be really careful about using ranges of char
s, because it doesn't really make any sense outside of ASCII letters and numbers.
Fifth, the compiler doesn't "throw". Nothing in the language throws; Rust doesn't have exceptions. That's a compile error. I'm just a little worried you might be under the impression Rust is interpreted or something.
Sixth, in the case of char == '0'...'5'
the problem is that you're now talking about inclusive ranges in an expression context, and those aren't stabilised yet. Basically, the core team hasn't decided if they're going to work like that. You can use exclusive ranges, though, which look like '0'..'6'
. However...
Seventh, that comparison doesn't make any sense. A char
can't be equal to a range of chars any more than 3
is equal to vec![1, 2, 3, 4, 5]
. What you want is to ask if char
is contained within the range '0'..'6'
, which you can work out once you realise that ..
in expressions is just shorthand for constructing the values of the various std::ops::Range*
types. In this specific case, it'd be a value of type Range<_>
. This tells you there's a Range::contains
method... but that's also unstable. So you'd need to do the comparison by hand by comparing char
to the range's start
and end
fields, and at that point, you might as well just write it out as a normal comparison.
The simplest way to do this is probably to use something like the matches
crate, which provides a macro that lets you use the same match pattern you're already using, but in an expression context, and returns a bool
.
By the way, you should be careful with char
range expressions too, because as I said, they don't really make much sense. Whilst you can construct a Range<char>
, you can't iterate over it due to char
not defining Step
or Add
.