I am a Rust beginner and I like the idea of having a construct like match were the exhaustiveness of what I write is checked but I incur in problems with the compiler for doing very simple things which are actually correct, like the following.
How should I handle this situation? (Code explains itself in this case)
fn main() {
let my_int = -29;
match my_int {
x if x < 10 => {println!("Foo")},
x if x >= 10 && x < 20 => {println!("Bar")},
x if x >= 20 => {println!("Baz")},
}
}
The compiler says:
error[E0004]: non-exhaustive patterns: `_` not covered
--> src/main.rs:3:11
|
3 | match my_int {
| ^^^^^^ pattern `_` not covered
|
= note: the matched value is of type `i32`
= note: match arms with guards don't count towards exhaustivity
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
6 ~ x if x >= 20 => {println!("Baz")},
7 ~ _ => todo!(),
|
>Solution :
This is because the usage of the condition doesn’t constrain the exhaustiveness of the types. But you can write this:
fn main() {
let my_int = -29;
match my_int {
..=9 => {println!("Foo")},
10..=19 => {println!("Bar")},
20.. => {println!("Baz")},
}
}
If you want to use x, you can do so like this:
fn main() {
let my_int = -29;
match my_int {
x @ ..=9 => {println!("Foo: {x}")},
x @ 10..=19 => {println!("Bar: {x}")},
x @ 20.. => {println!("Baz: {x}")},
}
}