Assignment from Rust match statement

為{幸葍}努か 提交于 2020-04-06 03:46:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!