how `if` chain comparing integers against a value can be rewritten with `match`?
fn test_if_else(c: i32) {
if c > 0 {
println!("The number {} is greater than zero", c);
} else if c < 0 {
println!("The number {} is less then zero", c);
} else {
println!("the number {} is equal to zero", c);
}
here's what happened to me
match c {
0 => println!("the number {} is equal to zero", c),
0..infinity => println!("The number {} is greater than zero", c),
_ => println!("the number {} is equal to zero", c)
}
but it doesn't work with 'infinity'
You just need to use an open range 0..
:
fn test_if_else(c: i32) {
match c {
0 => println!("the number {} is equal to zero", c),
0.. => println!("The number {} is greater than zero", c),
_ => println!("the number {} is lesser than zero", c),
}
}
Playground
You can also do this with an if c>0
guard, which is a little more flexible.
fn test_if_else(c: i32) {
match c {
0 => println!("the number {} is equal to zero", c),
c if c > 0 => println!("The number {} is greater than zero", c),
_ => println!("the number {} is lesser than zero", c),
}
}