📜  Rust – 枚举

📅  最后修改于: 2022-05-13 01:54:36.461000             🧑  作者: Mango

Rust – 枚举

Rust 中的枚举是一种自定义数据类型,它表示可以是多种可能变体中的任何一种的数据。枚举中的每个变体都可以选择有与之关联的数据。枚举类型是在枚举名称之前使用 enum 关键字定义的。它还由方法组成。

句法:

enum name_of_enum{
variant_1,
variant_2,
.
.
variant_n
}

这里的name_of_enum是赋予 Enum 的名称, variant_1variant_2 、…… variant_n是枚举的值。

例子:

enum Month_name{
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}

在上面的例子中, Month_name是枚举的名称,一月、二月、三月、四月、五月、六月、七月、八月、九月、十月、十一月、十二月是枚举的值。枚举的值可以匹配任何变体。出于这个原因,枚举有时被称为“和类型”:枚举的可能值集是每个变体的可能值集的总和。



让我们创建每个变体的实例。看起来像:

let jan = Month_name :: January;
let feb = Month_name :: February;
let mar = Month_name :: March;
let apr = Month_name :: April;
let may = Month_name :: May;
let jun = Month_name :: June;
let jul = Month_name :: July;
let aug = Month_name :: August;
let sep = Month_name :: September;
let oct = Month_name :: October;
let nov = Month_name :: November;
let dec = Month_name :: December;

枚举的每个变体都在其identifier下命名空间,并使用双冒号

让我们看一下代码。

Rust
// The `derive` attribute automatically creates the implementation
// required to make this `enum` printable with `fmt::Debug`.
#[derive(Debug)]
  
enum Month_name {
January,
February,
March,
April,
May,
June,
July,
August,
September,
October,
November,
December
}
fn main() {
    let jan = Month_name :: January;
    let feb = Month_name :: February;
    let mar = Month_name :: March;
    let apr = Month_name :: April;
    let may = Month_name :: May;
    let jun = Month_name :: June;
    let jul = Month_name :: July;
    let aug = Month_name :: August;
    let sep = Month_name :: September;
    let oct = Month_name :: October;
    let nov = Month_name :: November;
    let dec = Month_name :: December;
  
   println!("{:?}",jan);
   println!("{:?}",feb);
   println!("{:?}",dec);
}


输出:

January
February
December

在上面的例子中,Month_name 是枚举的名称。这里janfebdec是月份的名称,分别代表一月、二月和十二月的枚举 Month_name 的变体。