rust 基础03

枚举

定义

1
2
3
4
5
6
enum Message {
Quit, // 常量标识
Move{x:i32,y:i32}, // 匿名结构体
Write(String), // 字符串
ChangeColor(i32,i32,i32) // 元组或数组数据
}

定义方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum Message {
Quit, // 常量标识
Move{x:i32,y:i32}, // 匿名结构体
Write(String), // 字符串
ChangeColor(i32,i32,i32) // 元组或数组数据
}

impl Message{
fn call(&self){}
}

fn main() {
let q = Message::Quit;
let m = Message::Move { x: 20, y: 30 };
let w = Message::Write(String::from("hello"));
let c = Message::ChangeColor(200, 300, 400);

m.call();
}

Option枚举

1
2
3
4
5
// Option的定义
enum Option<T> {
None,
Some(T),
}
1
2
3
4
5
// Option枚举用例
let some_number = Some(5);
let some_string = Some("a string");

let absent_number: Option<i32> = None;

Match 匹配

举例

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
enum Week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}

fn main() {
let num = week_num(Week::Friday);
println!("{}",num)
}

fn week_num(w:Week) -> u8{
match w {
Week::Monday => 1,
Week::Tuesday => 2,
Week::Wednesday => 3,
Week::Thursday => 4,
Week::Friday => 5,
Week::Saturday => 6,
Week::Sunday => 7,
}
}
  • 注意:match匹配的值必须进行穷举,如果没必要都匹配的话使用 _ 匹配剩余的值
    1
    2
    3
    4
    5
    6
    7
    8
    fn week_num(w:Week) -> u8{
    match w {
    Week::Monday => 1,
    Week::Tuesday => 2,
    Week::Wednesday => 3,
    _ => 0
    }
    }

使用 mat处理option枚举数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
let five = Some(5);
let _six = plus_one(five);
let _none = plus_one(None);
}

fn plus_one(x:Option<i32>)-> Option<i32> {
match x {
None => {
println!("是个空值");
None
},
Some(i) => {
println!("{}",i);
Some(i+1)
}
}
}