关于模式匹配:Rust match语句中的赋值

Assignment from Rust match statement

Rust中是否有一个习惯用法,用于根据match子句分配变量的值? 我知道类似

1
2
3
4
val b = a match {
     case x if x % 2 == 1 => false
     case _ => true
}

来自Scala,想知道您是否可以在Rust中做同样的事情。 有没有一种方法可以将match子句评估为表达式并从中返回内容,或者仅仅是Rust中的一条语句?


在Rust中,几乎每个语句也是一个表达式。

你可以这样做:

1
2
3
4
5
6
7
fn main() {
    let a = 3;
    let b = match a {
        x if x % 2 == 1 => false,
        _ => true,
    };
}

操场


当然有:

1
2
3
4
5
6
7
8
9
10
fn main() {
    let a = 1;

    let b = match a % 2 {
        1 => false,
        _ => true
    };

    assert_eq!(b, false);
}

相关的Rust参考章节:匹配表达式。

尽管在您的情况下,简单的if就足够了:

1
let b = if a % 2 == 1 { false } else { true };

甚至

1
let b = a % 2 != 1;