枚举在Rust里是枚举很重要的一种类型,因为它体现了Rust的达式一个重要设计:必须处理空值和错误。先看普通的枚举枚举enum IpAddrKind {
V4,
V6,
}
let four = IpAddrKind::V4;
let six = IpAddrKind::V6;这里的V4和V6称为IpAddrKind的变体。C的达式枚举实际上是整型,但前面说过Rust是枚举强类型语言,类型互转是达式很困难的。每个enum变体都可以选择绑定一个数据,枚举这个设计有什么用呢?enum Message {
Quit,达式
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}内置的Option枚举enum Option
Some(T),
None,
}Option表示的是,可能有值也可能没有值的枚举情况,如果有值,达式这个值在Some里,枚举如果没有值,达式那就是枚举None十亿美元的错误In his 2009 presentation “Null References: The Billion Dollar Mistake,” Tony Hoare, the inventor of null, has this to say:I call it my billion-dollar mistake. At that time, I was designing the first comprehensive type system for references in an object-oriented language.My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.如果一个表达式返回了Option类型,要想从里面获取结果,达式就必须要处理空值情况,枚举否则编译器就会报错。fn plus_one(x: Option
match x {
Some(i) => Some(i + 1),
}
}$ cargo run
Compiling enums v0.1.0 (file:///projects/enums)
error[E0004]: non-exhaustive patterns: `None` not covered
--> src/main.rs:3:15
|
3 | match x {
| ^ pattern `None` not covered
|
= help: ensure that all possible cases are being handled, possibly by adding wildcards or more match arms
= note: the matched value is of type `Option
error: aborting due to previous error内置的Result枚举Result用于返回一个结果,但也有可能出错的情况,使用枚举,就要求调用方要显式地处理错误。enum Result
Ok(T),
Err(E),
}比如打开一个文件use std::fs::File;
fn main() {
let f: u32 = File::open("hello.txt");
}可是没有输出令人兴奋的结果$ cargo run
Compiling error-handling v0.1.0 (file:///projects/error-handling)
error[E0308]: mismatched types
--> src/main.rs:4:18
|
4 | let f: u32 = File::open("hello.txt");
| --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `u32`, found enum `std::result::Result`
| |
| expected due to this
|
= note: expected type `u32`
found enum `std::result::Result
(责任编辑:焦点)