Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how `if` chain comparing integers against a value can be rewritten with `match`?

Tags:

rust

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'

like image 565
martyr Avatar asked Nov 01 '25 20:11

martyr


1 Answers

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

like image 85
Netwave Avatar answered Nov 04 '25 14:11

Netwave