“match” is a Rust keyword for pattern matching. At first, it seems similar to “switch” in other programming languages like C and Java. But it has more capabilities in Rust.
Match on basic types
Match may be used on simple numeric or string variables.
fn main() {
let st_number = "one";
match st_number {
"one" => {
println!("Number = {}", 1);
}
"two" => {
println!("Number = {}", 1);
}
"three" => {
println!("Number = {}", 1);
}
_ => {
println!("Unknown Number");
}
}
}
Match on enums
Match can be used like switch in other languages on enums. Enums in Rust may have inner variables, Match provides a way to access them. Option and Result have wide usage in Rust.
Use match on Option:
fn main() {
let variable: Option<i32> = Some(10);
match variable {
Some(value) => {
println!("Variable content: {}", value);
}
None => {
println!("Variable is empty");
}
}
}
Use match on Result:
fn main() {
let variable: Result<i32, String> = Ok(10);
match variable {
Ok(value) => {
println!("Result contains value: {}", value);
}
Err(err_var) => {
println!("Result has error. error: {}", err_var);
}
}
}
Bind to values of enum’s inner variables:
fn main() {
let number: Option<i32> = Some(1);
match number {
Some(n @ 1) => println!("one. {}", n),
Some(n @ 2) => println!("two. {}", n),
Some(n @ 3..10) => println!("Between 3 to 10. {}", n),
Some(n) => println!("Not interesting inner value... {}", n),
_ => (),
}
}
Use Match as an inline function
Match may be used like inline function to map an object to another.
fn main() {
let st_value = "two";
let int_value = 1 + match st_value {
"one" => 1,
"two" => 2,
"three" => 3,
_ => 0
};
println!("{} + one = {}", st_value, int_value);
}
Multiple values and range
Multiple values may be used for matching.
fn main() {
let variable: i32 = 1;
let st_var = match variable {
0 | 1 | 2 => "Zero or One or Two",
3..=10 => "Between three up to equal to ten",
_ => "Greater than ten"
};
println!("{} = {}", variable, st_var);
}
Use “if” and functions inside match’s patterns
It’s possible to use “if” and functions inside patterns.
fn is_zero(v: u8) -> bool {
v == 0
}
fn main() {
let number: u8 = 4;
match number {
i if is_zero(i) => println!("Zero"),
i if i > 0 => println!("Greater than zero"),
_ => println!("Unknown value"),
}
}
Match by “Struct” content
If struct used for marching its possible to match it’s properties.
struct Foo {
p1: u32,
p2: u32,
}
fn main() {
let foo = Foo { p1: 1, p2: 2 };
match foo {
Foo { p1: 1, p2: x } => println!("p1=1 & p2={}", x),
Foo { p1: 2..10, p2: x } => println!("p1=2-10 & p2={}", x),
Foo { p1: .., p2: x } => println!("p1=any & p2={}", x),
}
}
More Information
More information may be found on Rust documentation.