Pattern Matching
Pattern matching is how you work with sum types and destructure data.
Match Statement
fn describe_option(opt: Option[i32]) -> string {
var result: string = ""
match opt {
Some(n) => { result = "Has value: " + to_string(n) }
None => { result = "Empty" }
}
return result
}
fn area(shape: Shape) -> f64 {
var result: f64 = 0.0
match shape {
Circle(r) => { result = 3.14159 * r * r }
Rectangle(w, h) => { result = w * h }
Triangle(a, b, c) => {
let s: f64 = (a + b + c) / 2.0
result = sqrt(s * (s - a) * (s - b) * (s - c))
}
}
return result
}Pattern Types
Wildcard Pattern
_ => { /* matches anything */ }Variable Pattern
x => { /* binds value to x */ }
n => { return n * 2 }Literal Patterns
match value {
0 => { result = "zero" }
1 => { result = "one" }
_ => { result = "other" }
}Constructor Patterns
match option {
Some(x) => { result = x }
None => { result = 0 }
}Record Patterns
match point {
Point { x: 0.0, y: 0.0 } => { result = "origin" }
Point { x: 0.0, y: y } => { result = "on y-axis" }
Point { x: x, y: 0.0 } => { result = "on x-axis" }
Point { x: x, y: y } => { result = "general point" }
}Tuple Patterns
match pair {
(0, 0) => { result = "origin" }
(x, 0) => { result = "on x-axis" }
(0, y) => { result = "on y-axis" }
(x, y) => { result = "general" }
}Or Patterns
match value {
1 | 2 | 3 => { result = "small" }
4 | 5 | 6 => { result = "medium" }
_ => { result = "large" }
}Guard Patterns
match value {
n if n < 0 => { result = "negative" }
n if n > 100 => { result = "large" }
n => { result = "normal" }
}Destructuring in Let
let p: Point = Point { x: 3.0, y: 4.0 }
let Point { x: px, y: py }: Point = p
let pair: (i32, string) = (42, "hello")
let (n, s): (i32, string) = pair