Rust 枚举

枚举的定义

  • enum 关键字来定义枚举
// 实现定义颜色枚举
enum Color {
    Red,
    Green,
    Blue,
    Yellow
}

// 定义获取得到对应颜色值
let colorRed = Color::Red;
let colorGreen = Color::Green;
let colorBlue = Color::Blue;
let colorYellow = Color::Yellow;

// 使用match 关键字进行匹配输出
match colorRed {
    Color::Red => println!("red"),
    Color::Green => println!("green"),
    Color::Blue => println!("blue"),
    Color::Yellow => println!("yellow"),
}

// 使用 impl 关键字来实现枚举的方法
impl Color {
    fn get_color(&self) -> &str {
        match self {
            Color::Red => "red",  // return "red"
            Color::Green => "green",  // return "green"
            Color::Blue => "blue",   // return "blue"
            Color::Yellow => "yellow",   // return "yellow"
        }
    }
}

// 使用自定义的方法
let color = Color::Red;
let color_name = color.get_color();

枚举和match构造

  • 首先对于我们的枚举的数据类型的话是无法直接通过 if == 进行操作的,此时只有通过 match 构造函数来实现间接性的获得所有的输出或者操作情况
  • 但是需要注意的是 enum 的 match 必须实现全部的情况,否则会报错,不要处理的直接使用_ 作为替代就行了
// 定义枚举数据
enum Direction {
    Up,  // 上
    Down,  // 下
    Left,  // 左
    Right,  // 右
}

// 定义一个函数,根据方向进行移动
fn move_player(direction: Direction) -> &'static str {
    match direction {
        Direction::Up => "向上移动",
        Direction::Down => "向下移动",
        Direction::Left => "向左移动",
        Direction::Right => "向右移动",
    }
}

// 获取枚举数据
let direction = Direction::Up;
let move_result = move_player(direction);
println!("{}", move_result);

数据枚举

  • 先来一段 rust 代码
enum Result {
    Sucess(f64),
    Error(u16, char),
    Uncertainty,
}

let outcome = Result::Error(1200, 'X');

// 实现使用 match 
match outcome {
    Result::Sucess(value) => println!("成功,结果为:{}", value),
    Result::Error(code, ch) => println!("错误,错误码为:{},错误信息为:{}", code, ch),
    Result::Uncertainty => println!("不确定性"),
}
  • 上诉的代码类似于 C 语言中 enum + union 的组合
#include<stdio.h>

// 定义枚举
enum eResult {
    Sucess,
    Error,
    Uncertainty,
};

// 定义联合体
union uResult {
    enum eResult type;
    struct {
        double value;
        struct {
            unsigned short code;
            char ch;
        } error;
    } data;
} outcome;

// 初始化联合体
outcome.type = Error;
outcome.data.error.code = 1200;
outcome.data.error.ch = 'X';


int main() {
    switch (outcome.type) {
        case Sucess:
            printf("成功,结果为:%f\n", outcome.data.value);
            break;
        case Error:
            printf("错误,错误码为:%d,错误信息为:%c\n", outcome.data.error.code, outcome.data.error.ch);
            break;
        case Uncertainty:
            printf("不确定性\n");
            break;
    }

    return 0;
}