02-C 风格用法

C 风格用法 — Rust By Example

译文 · 基于 Rust By Example

原文链接: https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum/c_like.html

C 风格用法

enum 也可以像 C 语言风格的枚举类型那样使用。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 该属性用于隐藏对未使用代码的警告。
#![allow(dead_code)]

// 拥有隐式辨别值(implicit discriminator,从 0 开始)的 enum
enum Number {
    Zero,
    One,
    Two,
}

// 拥有显式辨别值(explicit discriminator)的 enum
enum Color {
    Red = 0xff0000,
    Green = 0x00ff00,
    Blue = 0x0000ff,
}

fn main() {
    // `enum` 可以转成整型。
    println!("zero is {}", Number::Zero as i32); // zero is 0
    println!("one is {}", Number::One as i32); // one is 1

    println!("roses are #{:06x}", Color::Red as i32); // roses are #ff0000
    println!("violets are #{:06x}", Color::Blue as i32); // violets are #0000ff
}

参考:

类型转换

最后修改 October 2, 2026: 更新 (f3447ada6)