Is there an idiom in Rust which is used to assign the value of a variable based on a match clause? I know something like
val b = a match {
case x if x % 2 == 1 => false
case _ => true
}
from Scala and was wondering whether you can do the same in Rust. Is there a way to evaluate a match clause as an expression and return something from it or is it just a statement in Rust?
Match Statement in Rust We will start with the keyword match, and then compare the variable to use the match construct. We then open the match body, which takes the case as a “matched” value against the specified variable's value. In the previous example, we start by initializing the variable age.
Rust has a keyword, match , that allows you to replace complicated if / else groupings with something more powerful. Check it out: #![allow(unused_variables)] fn main() { let x = 5; match x { 1 => println!(" one"), 2 => println!("
Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.
A match expression has a scrutinee expression, which is the value to compare to the patterns. The scrutinee expression and the patterns must have the same type. A match behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.
In Rust, nearly every statement is also an expression.
You can do this:
fn main() {
let a = 3;
let b = match a {
x if x % 2 == 1 => false,
_ => true,
};
}
Playground
Sure there is:
fn main() {
let a = 1;
let b = match a % 2 {
1 => false,
_ => true
};
assert_eq!(b, false);
}
Relevant Rust Reference chapter: match expressions.
Though in your case a simple if
would suffice:
let b = if a % 2 == 1 { false } else { true };
or even
let b = a % 2 != 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With