Rust - Basic - 06 - Enum

Enum

Comprehension

  • 基础语法

    // 基础声明
    enum IpAddrKind {
        V4,
        V6,
    }
    // 基础使用
    let four = IpAddrKind::V4;
    let six = IpAddrKind::V6;
    
    // 可用于 struct
    struct IpAddr {
        kind: IpAddrKind,
        address: String,
    }
    
    // 可包含不同 Type,包括 struct
    enum IpAddr {
        V4(u8, u8, u8, u8),
        V6(String),
    }
    let home = IpAddr::V4(127, 0, 0, 1);
    let loopback = IpAddr::V6(String::from("::1"));
    struct Ipv4Addr {
        // --snip--
    }
    struct Ipv6Addr {
        // --snip--
    }
    enum IpAddr {
        V4(Ipv4Addr),
        V6(Ipv6Addr),
    }
    enum Message {
        Quit,
        Move { x: i32, y: i32 },
        Write(String),
        ChangeColor(i32, i32, i32),
    }
    
    // 和 struct 一样,支持 impl
    impl Message {
        fn call(&self) {
            // method body would be defined here
        }
    }
    
  • 与 match 结合使用

    match 必须囊括所有的可能枚举值

    如果不列出所有可能枚举值,可以用其他变量或下划线代替

    match 语句返回的值 Type 需要一致

    注意 match 也会触发 move

    关于 match 的其他使用方式,在其他章节说明

    #[derive(Debug)]
    enum UsState {
        Alabama,
        Alaska,
        // --snip--
    }
    #[derive(Debug)]
    enum Coin {
        Penny,
        Nickel,
        Dime,
        Quarter(UsState),
    }
    fn value_in_cents(coin: Coin) -> u8 {
        match coin {
            Coin::Penny => 1,  // 只有一行的时候,可以省略 {}
            Coin::Nickel => 5,
            Coin::Dime => 10,
            Coin::Quarter(state) => {
    						// 这里的值可能为 UsState::Alabama 或 UsState::Alaska
                println!("State quarter from {:?}!", state);
                25
            }
        };
        match coin {
            Coin::Penny => 1,
    				// 可用其他变量,表示其他情况
            a => {
                println!("{:?}", a);
                5
            },
        };
        match coin {
            Coin::Penny => 1,
    				// 可用下划线
            _ => 5,
        }
    }
    
  • 与 if let 结合使用

    let mut count = 0;
    
    // match 写法
    match coin {
        Coin::Quarter(state) => println!("State quarter from {:?}!", state),
        _ => count += 1,
    }
    
    // if let 写法
    if let Coin::Quarter(state) = coin {
        println!("State quarter from {:?}!", state);
    } else {
        count += 1;
    }
    

Origin

https://doc.rust-lang.org/book/ch06-00-enums.html