在Rust中是否有一种习语用于基于匹配条件分配变量的值?我知道类似于
val b = a match {
case x if x % 2 == 1 => false
case _ => true
}
我来自Scala,并想知道你是否可以在Rust中做到同样的事情。有没有一种方法可以将match子句评估为表达式并从中返回某些内容,或者它在Rust中只是一个语句?
在Rust中是否有一种习语用于基于匹配条件分配变量的值?我知道类似于
val b = a match {
case x if x % 2 == 1 => false
case _ => true
}
我来自Scala,并想知道你是否可以在Rust中做到同样的事情。有没有一种方法可以将match子句评估为表达式并从中返回某些内容,或者它在Rust中只是一个语句?
Rust中,几乎每个语句都是一个表达式。
你可以这样做:
fn main() {
let a = 3;
let b = match a {
x if x % 2 == 1 => false,
_ => true,
};
}
:游乐场。fn main() {
let a = 1;
let b = match a % 2 {
1 => false,
_ => true
};
assert_eq!(b, false);
}
if
就足够了。let b = if a % 2 == 1 { false } else { true };
甚至更多
let b = a % 2 != 1;