问题
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?
回答1:
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
回答2:
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;
来源:https://stackoverflow.com/questions/42222655/assignment-from-rust-match-statement