枚举

时间:2024-02-20 07:44:03

C++、Python有枚举类型
rust的语法,

enum PokerSuit {
  Clubs,
  Spades,
  Diamonds,
  Hearts,
}

与C++相似,枚举值也可以带有值,

enum PokerCard {
    Clubs(u8),
    Spades(u8),
    Diamonds(u8),
    Hearts(u8),
}

fn main() {
   let c1 = PokerCard::Spades(5);
   let c2 = PokerCard::Diamonds(13);
}

rust的枚举类型可以用任何类型做成员,太强大了。

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

fn main() {
    let m1 = Message::Quit;
    let m2 = Message::Move{x:1,y:1};
    let m3 = Message::ChangeColor(255,255,0);
}

C语言中有null,指空值;而rust语言抛弃了null,改用Option枚举变量来表达,

fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);