Reputation: 5557
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?
Upvotes: 18
Views: 20007
Reputation: 14061
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,
};
}
Upvotes: 29
Reputation: 22283
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;
Upvotes: 7