走进 Rust:枚举

Rust About 1,495 words

定义枚举

#[derive(Debug)]
enum IpAddrKind {
    V4,
    V6,
}

使用枚举

枚举同样可以使用impl来实现结构体中的方法功能。

fn main() {
    let m = Message::Write(String::from("hello"));
    m.call();
}

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

impl Message {
    fn call(&self) {
        // method body would be defined here
    }
}

模式匹配

必须全匹配,若缺少一项,比如None,编译将无法通过。

#[derive(Debug)]
enum UsState {
    Alabama,
    Alaska,
}

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) => {
            println!("State quarter from {:?}!", state);
            25
        },
    }
}

fn main() {
    value_in_cents(Coin::Quarter(UsState::Alabama));
}

搭配 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);

_占位符

可以使用_来代替默认行为,否则将无线穷举。

let some_u8_value = 0u8;
match some_u8_value {
    1 => println!("one"),
    3 => println!("three"),
    5 => println!("five"),
    7 => println!("seven"),
    _ => (),
}

if let

使用if let可以简化匹配。

let mut count = 0;
if let Coin::Quarter(state) = Coin::Quarter(UsState::Alaska) {
    println!("State quarter from {:?}!", state);
} else {
    count += 1;
}
Views: 2,755 · Posted: 2020-07-13

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh