Rust-Lang Book Ch.6 Enum and Pattern Matching

Enum的定义和实例化

enum IpAddrKind {
    V4,
    V6,
}

    let four = IpAddrKind::V4;
    let six = IpAddrKind::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"),
    };

  

但是enum还可以有关联的struct,这样就可以减少额外声明一个struct了。

struct QuitMessage; // unit struct
struct MoveMessage {
    x: i32,
    y: i32,
}
struct WriteMessage(String); // tuple struct
struct ChangeColorMessage(i32, i32, i32); // tuple struct

  

match

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,//match arm, Coin::Penny是Pattern, =>分割Pattern和表达式
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {:?}!", state);//能获取内部数值
            25
        }
    }
}

  

注意在Rust中,必须处理所有可能,如果不能处理所有可能,就要使用placeholder "_",或者如果只关心一种,就要使用if let。

    let some_u8_value = 0u8;
    match some_u8_value {
        1 => println!("one"),
        3 => println!("three"),
        5 => println!("five"),
        7 => println!("seven"),
        _ => (),//() unit value,什么也不会发生
    }

If let

    if let Some(3) = some_u8_value {
        println!("three");
    }

  

可以加上else

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

  

Option

Rust没有null,而Option<T>中的None充当了Null的角色。

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

  

    let some_number = Some(5);
    let some_string = Some("a string");

    let absent_number: Option<i32> = None;//必须声明类型,不然编译器不知道具体

  

程序员在使用Option<T>做正常调用之前,必须先手动将Option<T>转化为T,这一步就减少了潜在的bug。

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

  

原文地址:https://www.cnblogs.com/xuesu/p/13871802.html