Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use statements in pattern matching branch?

Tags:

rust

Is it possible to have statements in pattern matching branch?

I tried this, but it doesn't work. Maybe there is some special syntax for achieving this?

fn main() {
    let x = 5i;

    match x {
        1 => println!("one"),
        _ => println!("something"); // error: expected one of `,`, `}`, found `;`
             println!("else"),
    }
}
like image 483
ave Avatar asked Oct 24 '14 08:10

ave


People also ask

Why pattern matching is better?

The advantage of pattern matching is that it is very flexible and powerful at the same time. Within the pattern, the data structure can be dynamically disassembled. These parts can then be assigned directly to variables that only apply within this expression.

What is expression match?

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.

How match works in rust?

Rust has an extremely powerful control-flow operator called match that allows us to compare a value against a series of patterns and then execute code based on which pattern matches.

What languages have pattern matching?

Early programming languages with pattern matching constructs include COMIT (1957), SNOBOL (1962), Refal (1968) with tree-based pattern matching, Prolog (1972), SASL (1976), NPL (1977), and KRC (1981).


Video Answer


1 Answers

If you want multiple statements you have to use {}:

fn main() {
    let x = 5i;

    match x {
        1 => println!("one"),
        _ => {
            println!("something");
            println!("else")
        }
    }
}
like image 109
Arjan Avatar answered Oct 02 '22 14:10

Arjan