18

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?

4
  • Straight from the Rust Book: 4.14 Match (2nd example). I advise you read the book (or at least check it when you have a question). Commented Feb 14, 2017 at 10:27
  • 2
    tbh I find the notion honorable, but the book hardly useful (I actually checked, but checked the pattern matching section, which has no example with an assignment). The book is very hard to search and misses a keyword index. I asked because I got some completely unrelated error message out of the compiler, since I forgot the colon after the first clause, and google returned no useful information. Commented Feb 14, 2017 at 22:10
  • 1
    @MatthieuM. It's hard to search for a specific answer like that as there are so much new things and concepts in rust Commented Mar 17, 2022 at 12:19
  • 2
    @Fayeure: Indeed; I still recommend reading the book anyway, but fully understand that just because someone's read it doesn't mean they remember every single piece of information nor that they can find it back. I... don't think I do, to be honest ;) Commented Mar 17, 2022 at 13:27

2 Answers 2

29

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

Sign up to request clarification or add additional context in comments.

Comments

7

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.