Lesson 13-Match
Match Statements in Rust: A Comprehensive Guide
The match statement in Rust provides functionality similar to the switch statement found in Javascript and other languages. It allows for branching execution based on multiple conditions, where each condition corresponds to a specific case. In essence, it can be viewed as a structured collection of if statements.
However, unlike Javascript’s switch, the conditions in Rust’s match cannot represent ranges.
The general syntax is as follows:
match variable {
condition => expression,
_ => expression
}
Here, the underscore _ serves as a placeholder, analogous to the default case in a switch statement, handling any values that do not match the preceding conditions.
Let’s illustrate the basic usage with an example:
Basic Usage
fn main() {
let a = 1;
let result = match a {
1 => "one",
2 => "two",
_ => "many"
};
println!("{}", result);
}
// Output:
// one
Integrating with Option Types
Now, let’s explore how to use match with Option types.
Since Option types must include both Some and None variants, the match statement must account for both possibilities to ensure exhaustiveness.
fn opt(val: Option<i8>) {
match val {
None => println!("None"),
Some(i) => {
println!("Some {}", i);
i
}
}
}
Omitting the None case will result in a compilation error due to non-exhaustive pattern matching.
Leveraging with Enum Types
One of the key strengths of match is its integration with enum types. We can assign values to the different variants of an enum, effectively “coloring” the enum with specific data.
Consider the following example:
enum Number {
One,
Two,
Three
}
fn count(num: Number) -> u8 {
match num {
Number::One => 1,
Number::Two => 2,
Number::Three => 3
}
}
Extending with Enhanced Enum Types
enum types can incorporate different data types as variants. We can utilize the match statement to effectively handle these diverse enum types.
enum Alphabet {
A,
B,
C
}
enum Number {
One,
Two,
Three(Alphabet)
}
fn count(num: Number) -> u8 {
match num {
Number::One => 1,
Number::Two => 2,
Number::Three(word) => {
println!("alphabet is {}", word);
3
}
}
}
fn main() {
let a = Number::Three(Alphabet::A);
let result = count(a);
println!("{}", result);
}
댓글남기기