Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if the expression in a match arm returns false?

Tags:

rust

This would be a nice fizzbuzz in Rust I think:

match (i % 3, i % 5) {
    (0, 0) => println!("FizzBuzz"),
    (0, _) => println!("Fizz"),
    (_, 0) => println!("Buzz"),
    _ => println!("{}", i),
}   

It could also be stated this way:

match i {
    i if i % 3 == 0 && i % 5 == 0 => println!("FizzBuzz"),
    i if i % 3 == 0 => println!("Fizz"),
    i if i % 5 == 0 => println!("Buzz"),
    _ => println!("{}", i),
}

Now that confused me.

i if i % 3 == 0

is an expression, right? So, this evaluates to i when the condition is true. But what happens if it is false?

like image 200
Rafael Bachmann Avatar asked Nov 16 '25 01:11

Rafael Bachmann


2 Answers

Now that confused me.

i if i % 3 == 0

is an expression, right?

No, it is not. It is a pattern (i) with a guard (i % 3 == 0). Maybe you got confused because you used the same bind name. Consider this modified example:

match i {
    x if x % 3 == 0 && x % 5 == 0 => println!("FizzBuzz"),
    x if x % 3 => println!("Fizz"),
    x if x % 5 => println!("Buzz"),
    _ => println!("{}", x),
}

You can read the match expression like this

  • If i matches the pattern x (it always match and i value is moved (copied) to x) and x % 3 == 0 and x % 5 == 0 then println!("FizzBuzz"); else
  • if i matches the pattern x and x % 3 == 0 then println!("Fizz"); else
  • if i matches the pattern x and x % 5 == 0 then println!("Buzz"); else
  • println!("{}", x)
like image 77
malbarbo Avatar answered Nov 17 '25 19:11

malbarbo


If it is false, the match arm is simply not called. These are called guards in the match statement. You can read about them in the book.

They are similar to an if-else but not in the case that there is an else block. They just add more filtering to the match blocks.

like image 40
squiguy Avatar answered Nov 17 '25 18:11

squiguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!