Rust : How to use `match` to replace nested if/else
When solving errors4.rs
exercise of rustlings, I initially used nested if/else.
It helps with readability.
While the solution was correct, clippy
suggested following:
help: consider rewriting the
if
chain withmatch
:match value.cmp(&0) {...}
I had used match
only with various possible values (mostly from Enum
) and
thus was unfamiliar with value.cmp(&0)
approach.
So I asked Gemini for a working example. 1
Here is the code is shared :
fn check_value(value: i32) {
match value.cmp(&0) {
std::cmp::Ordering::Less => {
println!("{} is less than zero.", value);
}
std::cmp::Ordering::Equal => {
println!("{} is exactly zero.", value);
}
std::cmp::Ordering::Greater => {
println!("{} is greater than zero.", value);
}
}
}
fn main() {
check_value(-5);
check_value(0);
check_value(10);
}
Moral of the story :
- Always use
clippy
when developing - Read all the errors carefully. Chances are there is plenty of information.
- Rust tooling is awesome! 😄
-
Turns out, clippy also pointed to exact documentation which also has a working code. But I didn’t pay attention. My bad. ↩︎