Skip to content

1.3 枚举

基础用法

rust
enum PokerSuit {
  Clubs,
  Spades,
  Diamonds,
  Hearts,
}
enum PokerSuit {
  Clubs,
  Spades,
  Diamonds,
  Hearts,
}
rust
fn main() {
    let heart = PokerSuit::Hearts;
    let diamond = PokerSuit::Diamonds;

    print_suit(heart);
    print_suit(diamond);
}

fn print_suit(card: PokerSuit) {
    println!("{:?}",card);
}
fn main() {
    let heart = PokerSuit::Hearts;
    let diamond = PokerSuit::Diamonds;

    print_suit(heart);
    print_suit(diamond);
}

fn print_suit(card: PokerSuit) {
    println!("{:?}",card);
}

带类型的枚举

  1. 基础类型
rust
enum PokerCard {
    Clubs(u8),
    Spades(u8),
    Diamonds(u8),
    Hearts(u8),
}
fn main() {
   let c1 = PokerCard::Spades(5);
   let c2 = PokerCard::Diamonds(13);
}
enum PokerCard {
    Clubs(u8),
    Spades(u8),
    Diamonds(u8),
    Hearts(u8),
}
fn main() {
   let c1 = PokerCard::Spades(5);
   let c2 = PokerCard::Diamonds(13);
}
  1. 复杂类型
rust
struct Ipv4Addr {
    // --snip--
}

struct Ipv6Addr {
    // --snip--
}

enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
struct Ipv4Addr {
    // --snip--
}

struct Ipv6Addr {
    // --snip--
}

enum IpAddr {
    V4(Ipv4Addr),
    V6(Ipv6Addr),
}
  1. 其他类型
rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

Option枚举

rust
enum Option<T> {
    Some(T),
    None,
}
enum Option<T> {
    Some(T),
    None,
}

Option枚举定义了,两种枚举值。所以它可能是Some,也可能是None。

对于Option类型的数据,可以接收SomeNone的值,例如:

rust
let num: Option<u8> = Some(12);
// 或
let num: Option<u8> = None;
let num: Option<u8> = Some(12);
// 或
let num: Option<u8> = None;

这代表,num它的值可能是空的,也可能有数字的值。

使用match对不同情况做处理

rust
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

获取Some的原始值

rust
let five = Some(5);
println!("{:?}", five.unwrap());

// 打印 5
let five = Some(5);
println!("{:?}", five.unwrap());

// 打印 5