枚举
Like tuples, enums can also be destructured by matching:
模式还可用于将变量绑定到值的某些部分。这是您检查类型结构的方式。我们先从简单的“enum”类型开始:
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}"), } }
在这里,我们使用了分支来解构“Result”值。在第一个分支中,“half”被绑定到“Ok”变体中的值。在第二个分支中,“msg”被绑定到错误消息。
- “if”/“else”表达式将返回一个枚举,该枚举之后会使用“match”进行解封装。
- 您可以尝试在枚举定义中添加第三个变体,并在运行代码时显示错误。指出代码现在有哪些地方还不详尽,并说明编译器会如何尝试给予提示。
- The values in the enum variants can only be accessed after being pattern matched.
- Demonstrate what happens when the search is inexhaustive. Note the advantage the Rust compiler provides by confirming when all cases are handled.