Rust Note(12) enum(I)

enum (enumeration) 枚舉


另外一種型態的類似 struct 結構體概念。
不完全相同,也不完全不同。

struct 結構體


複習一下struct 的概念

用於結構化一個物件,將其特性&&型態標示出來。
可用 impl 來對 struct 構建方法並使用結構體裡面的參數。

enum 枚舉


把可能的對象一一的舉例,就是枚舉
等同 struct, 可用impl 實作方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 把一週天都枚舉出來
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}

// 實作Day
impl Day {
// 返回true or false
fn is_weekday(&self) -> bool {
// 使用 match, 匹配自己
match self {
// 使用運算符 | or 只要有一個條件成立,即為true
&Day::Saturday | &Day::Sunday => return false,
_ => return true
// `_` other的意思
}
}
}

fn main() {
// 賦值 d
let d = Day::Sunday;
println!("Is d weekday? {}", d.is_weekday());
}

// output: Is d weekday? false

簡單的搭配 match , 簡化了 if else 判斷。

使用 trait for enum


那可以搭配 trait ?
可以的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//  把實例枚舉出來
#[derive(Debug)]
enum Day {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}

// 抽象化一層特質(trait) 為動作
trait Action {
fn actl(&self) -> &str;
}

// 實作 impl
impl Action for Day {
// return &str type
fn actl(&self) -> &str {
// match self
match self {
// by using | or operator
&Day::Saturday | &Day::Sunday => "I sleep all day!",
// "_" equal the other
_ => "I must work hard."
}
}
}

fn main() {
let today = Day::Monday;
let other_day = Day::Sunday;
println!("Today is {:?}, {}", today, today.actl());
println!("Tomorrow is {:?}, {}.", other_day, other_day.actl());
}

// output: Today is Monday, I must work hard.
// output: Tomorrow is Sunday, I sleep all day.

下一篇加入一點點不一樣的連結轉變.

Rust Note_20211125 for enum(I)