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"),
}
}
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.
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.
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.
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).
If you want multiple statements you have to use {}
:
fn main() {
let x = 5i;
match x {
1 => println!("one"),
_ => {
println!("something");
println!("else")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With