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();
if
==
进行操作的,此时只有通过 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);
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!("不确定性"),
}
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;
}