Rust Enums
Enums in Rust are not as simple a concept as in other programming languages, but they can still be used very simply:
Example
[
derive
(
Debug
)
]
enum
Book
{
Papery
,
Electronic
}
fn
main
(
)
{
let
book
=
Book
::
Papery
;
println
!
(
"{:?}"
,
book
)
;
}
Running result:
Papery
Books are divided into paper books (Papery book) and e-books (Electronic book).
If you are developing a library management system and need to describe the different attributes of the two kinds of books (a paper book has a call number, an e-book only has a URL), you can add tuple attribute descriptions to enum members:
enum Book {
Papery(u32),
Electronic(String),
}
let book = Book::Papery(1001);
let ebook = Book::Electronic(String::from("url://..."));
If you want to name the attributes, you can use struct syntax:
enum Book {
Papery { index: u32 },
Electronic { url: String },
}
let book = Book::Papery{index: 1001};
Although you can name them this way, please note that you cannot access attributes bound to an enum the same way you access struct fields. The way to access them is in match syntax.
match Syntax
The purpose of an enum is to classify a certain category of things, and the purpose of classification is to describe different situations. Based on this principle, enums are often ultimately handled by branch structures (switch in many languages). The switch syntax is classic, but it is not supported in Rust. The reason many languages abandon switch is that switch is prone to "fall-through" problems caused by forgetting to add break, and languages such as Java and C# prevent this through safety checks.
Rust implements branch structures through the match statement. First, let's see how to handle enums with match:
Example
fn
main
(
)
{
enum
Book
{
Papery
{
index
:
u32
}
,
Electronic
{
url
:
String
}
,
}
let
book
=
Book
::
Papery
{
index
:
1001
}
;
let
ebook
=
Book
::
Electronic
{
url
:
String
::
from
(
"url..."
)
}
;
match
book
{
Book
::
Papery
{
index
}
=>
{
println
!
(
"Papery book {}"
,
index
)
;
}
,
Book
::
Electronic
{
url
}
=>
{
println
!
(
"E-book {}"
,
url
)
;
}
}
}
Result:
Papery book 1001
A match block can also be treated as a function expression, and it can also have a return value:
match 枚举类实例 {
分类1 => 返回值表达式,
分类2 => 返回值表达式,
...
}
But all return-value expressions must have the same type!
If an enum's attached attributes are defined as a tuple, you need to temporarily specify a name in the match block:
Example
enum
Book
{
Papery
(
u32
)
,
Electronic
{
url
:
String
}
,
}
let
book
=
Book
::
Papery
(
1001
)
;
match
book
{
Book
::
Papery
(
i
)
=>
{
println
!
(
"{}"
,
i
)
;
}
,
Book
::
Electronic
{
url
}
=>
{
println
!
(
"{}"
,
url
)
;
}
}
Besides branching on enums, match can also branch on data of integer, floating-point, character, and string slice reference (&str) types. Among these, although branching on floating-point types is legal, it is not recommended because precision issues may lead to incorrect branches.
When branching on non-enum types, you must be careful to handle the exceptional case, even if there is nothing to do in that case. The exceptional case is represented by the underscore _:
Example
fn
main
(
)
{
let
t
=
"abc"
;
match
t
{
"abc"
=>
println
!
(
"Yes"
)
,
_
=>
{
}
,
}
}
The Option Enum
Option is an enum in the Rust standard library, used to fill the gap left by Rust's lack of null references.
Many languages support the existence of null (C/C++, Java), which is convenient but also creates great problems. The inventor of null admitted this: "a convenient idea that caused cumulative losses of 1 billion dollars".
null often delivers a fatal blow to a program when developers assume everything is not null: after all, as soon as one such error occurs, the program's execution will terminate completely.
To solve this problem, many languages do not allow null by default, but support the appearance of null at the language level (often modified with a ? symbol before the type).
Java supports null by default, but can restrict the appearance of null through the @NotNull annotation, which is a stopgap measure.
Rust completely disallows the existence of the null value at the language level. But since null can efficiently solve a small number of problems, Rust introduced the Option enum:
enum Option {
Some(T),
None,
}
If you want to define a type that can have an empty value, you can do this:
let opt = Option::Some("Hello");
If you want to perform some operation on opt, you must first determine whether it is Option::None:
Example
fn
main
(
)
{
let
opt
=
Option
::
Some
(
"Hello"
)
;
match
opt
{
Option
::
Some
(
something
)
=>
{
println
!
(
"{}"
,
something
)
;
}
,
Option
::
None
=>
{
println
!
(
"opt is nothing"
)
;
}
}
}
Running result:
Hello
If your variable is empty at the beginning, be considerate of the compiler: how could it know what type the variable is when the value is not empty?
Therefore, an Option whose initial value is empty must have an explicit type:
Example
fn
main
(
)
{
let
opt
:
Option
<&
str
=
Option
::
None
;
match
opt
{
Option
::
Some
(
something
)
=>
{
println
!
(
"{}"
,
something
)
;
}
,
Option
::
None
=>
{
println
!
(
"opt is nothing"
)
;
}
}
}
Running result:
opt is nothing
This design makes programming with empty values less easy, but this is exactly what is needed to build a stable and efficient system. Since Option is introduced by the Rust compiler by default, when using it you can omit Option:: and write None or Some() directly.
Option is a special enum that allows branching on whether it contains a value:
Example
fn
main
(
)
{
let
t
=
Some
(
64
)
;
match
t
{
Some
(
64
)
=>
println
!
(
"Yes"
)
,
_
=>
println
!
(
"No"
)
,
}
}
if let Syntax
Example
let
i
=
0
;
match
i
{
0
=>
println
!
(
"zero"
)
,
_
=>
{
}
,
}
Put it into the main function and run the result:
zero
The purpose of this program is to determine whether i is the number 0, and if so, print zero.
Now use if let syntax to shorten this code:
let i = 0;
if let 0 = i {
println!("zero");
}
The if let syntax has the following format:
if let 匹配值 = 源变量 {
语句块
}
You can add an else block afterward to handle the exceptional case.
The if let syntax can be considered "syntactic sugar" for a match statement that only distinguishes two cases (syntactic sugar refers to a convenient alternative with the same underlying principle as some syntax).
It still applies to enums:
Example
fn
main
(
)
{
enum
Book
{
Papery
(
u32
)
,
Electronic
(
String
)
}
let
book
=
Book
::
Electronic
(
String
::
from
(
"url"
)
)
;
if
let
Book
::
Papery
(
index
)
=
book
{
println
!
(
"Papery {}"
,
index
)
;
}
else
{
println
!
(
"Not papery book"
)
;
}
}