Destructuring Enums

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:

  1. enum Result {
  2. Ok(i32),
  3. Err(String),
  4. }
  5. fn divide_in_two(n: i32) -> Result {
  6. if n % 2 == 0 {
  7. Result::Ok(n / 2)
  8. } else {
  9. Result::Err(format!("cannot divide {n} into two equal parts"))
  10. }
  11. }
  12. fn main() {
  13. let n = 100;
  14. match divide_in_two(n) {
  15. Result::Ok(half) => println!("{n} divided in two is {half}"),
  16. Result::Err(msg) => println!("sorry, an error happened: {msg}"),
  17. }
  18. }

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.

Key points:

  • The if/else expression is returning an enum that is later unpacked with a match.
  • You can try adding a third variant to the enum definition and displaying the errors when running the code. Point out the places where your code is now inexhaustive and how the compiler tries to give you hints.