Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1
Tips and Traps¶
match
does a pattern matching which means each branch must be a pattern instead of an expression. Please refer to Patterns Are Not Expressions for differences between patterns and expressions.Avoid using the identifier pattern and
_
in a pattern match especially when you work with a Enum. Keep in mind that explicit is better than implicit.
The following match
statement won't compile because 0 + 1
is NOT a pattern.
let x = 1;
match x {
0 + 1 => "how",
_ => "are",
}
let x = 1;
(match x {
0 => 100,
_ => 1000,
} + 1)
The following match statement is problematic
as y
is an identifier pattern which is irrefutable.
In another words,
y
will match anything and the branch _ => "are"
will never be reached.
let x = 1;
fn f(x: i32) -> i32 {
x
}
let y = f(1);
match x {
y => "how",
_ => "are",
}
Match Guards¶
You can use match guards to mimic an if/else
or switch
statement.
The following is a if/else
like match
statement even if it is not as concise.
let x = 1;
match x {
v if v == 0 => "how",
v if v == 1 => "are",
_ => "you",
}
let x = 10;
match x {
v if v == 0 => "how",
v if v == 1 => "are",
_ => "you",
}
Matching Literals¶
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
Matching Range¶
Destruct Struct and Matching¶
struct Pair {
x: u32,
y: u32,
}
let p = Pair{x: 0, y: 1};
let Pair{x: v1, y: v2} = p;
v1
v2
let Pair{x: x1, y: x2} = Pair{x: 100, y: 200};
x1
x2