Rust 编程视频教程对应讲解内容-枚举类型与匹配

视频地址

头条地址:https://www.ixigua.com/i6765442674582356483
B站地址:https://www.bilibili.com/video/av78062009?p=1
网易云课堂地址:https://study.163.com/course/introduction.htm?courseId=1209596906#/courseDetail?tab=1

讲解内容

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!");
}

你可能感兴趣的:(Rust 编程视频教程对应讲解内容-枚举类型与匹配)