Rust 程式設計影片教程對應講解內容-列舉型別與匹配

linghuyichong發表於2019-12-26

頭條地址:https://www.ixigua.com/i676544267458235648...
B站地址:https://www.bilibili.com/video/av78062009?...
網易雲課堂地址:https://study.163.com/course/introduction....

1、類似於c語言的方式

enum IpAddrKind {
    V4,
    V6,
}

struct IpAddr {
    kind: IpAddrKind,
    address: String,
}

let home = IpAddr {
    kind: IpAddrKind::V4,
    address: String::from("127.0.0.1"),
};

let loopback = IpAddr {
    kind: IpAddrKind::V6,
    address: String::from("::1"),
};

2、rust提倡的方式

enum IpAddr {
    V4(String),
    V6(String),
}

let home = IpAddr::V4(String::from("127.0.0.1"));
let loopback = IpAddr::V6(String::from("::1"));

3、可以是不同型別

enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);
let loopback = IpAddr::V6(String::from("::1"));

4、經典用法

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

解釋:

  • Quit 沒有關聯任何資料。
  • Move 包含一個匿名結構體。
  • Write 包含單獨一個 String。
  • ChangeColor 包含三個 i32。

等同於(用結構體的話):

struct QuitMessage; // 類單元結構體
struct MoveMessage {
    x: i32,
    y: i32,
}
struct WriteMessage(String); // 元組結構體
struct ChangeColorMessage(i32, i32, i32); // 元組結構體

5、列舉型別的方法,以及match

enum Message<> {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangColor(i32, i32, i32),
}

impl Message{
    fn prin(&self) {
        match *self {
            Message::Quit => println!("Quit"),
            Message::Move{x, y} => println!("Move x = {}, y = {}", x, y),
            Message::ChangColor(a, b, c) => println!("a = {}, b = {}, c = {}", a, b, c),
            //Message::Write(&s) => println!("Write s = {}", s.to_string())
            _ => println!("string!")
        }
    }
}

fn main() {
    let quit = Message::Quit;
    quit.prin();
    let mov = Message::Move{x: 10, y: 20};
    mov.prin();
    let wri = Message::Write(String::from("Write some thing!"));
    wri.prin();
    let change = Message::ChangColor(1, 2, 3);
    change.prin();
    println!("Hello, world!");
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章