Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment from Rust match statement

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?

like image 315
midor Avatar asked Feb 14 '17 09:02

midor


People also ask

How do I use a match statement in Rust?

Match Statement in Rust We will start with the keyword match, and then compare the variable to use the match construct. We then open the match body, which takes the case as a “matched” value against the specified variable's value. In the previous example, we start by initializing the variable age.

What is match keyword in Rust?

Rust has a keyword, match , that allows you to replace complicated if / else groupings with something more powerful. Check it out: #![allow(unused_variables)] fn main() { let x = 5; match x { 1 => println!(" one"), 2 => println!("

Does Rust have pattern matching?

Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.

What is match expression?

A match expression has a scrutinee expression, which is the value to compare to the patterns. The scrutinee expression and the patterns must have the same type. A match behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.


2 Answers

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

like image 58
Chris Emerson Avatar answered Oct 06 '22 20:10

Chris Emerson


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;
like image 25
ljedrz Avatar answered Oct 06 '22 19:10

ljedrz