src/pattern-matching/destructuring-enums.md
Like tuples, enums can also be destructured by matching:
Patterns can also be used to bind variables to parts of your values. This is how
you inspect the structure of your types. Let us start with a simple enum type:
# // Copyright 2022 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
enum Result {
Ok(i32),
Err(String),
}
fn divide_in_two(n: i32) -> Result {
if n % 2 == 0 {
Result::Ok(n / 2)
} else {
Result::Err(format!("cannot divide {n} into two equal parts"))
}
}
fn main() {
let n = 100;
match divide_in_two(n) {
Result::Ok(half) => println!("{n} divided in two is {half}"),
Result::Err(msg) => println!("sorry, an error happened: {msg}"),
}
}
Here we have used the arms to destructure the Result value. In the first
arm, half is bound to the value inside the Ok variant. In the second arm,
msg is bound to the error message.
if/else expression is returning an enum that is later unpacked with a
match.match. Point out how this is syntactically similar to
matching on a struct.