枚举
enum
关键字允许创建具有几个 不同变体的类型:
fn generate_random_number() -> i32 { // Implementation based on https://xkcd.com/221/ 4 // Chosen by fair dice roll. Guaranteed to be random. } #[derive(Debug)] enum CoinFlip { Heads, Tails, } fn flip_coin() -> CoinFlip { let random_number = generate_random_number(); if random_number % 2 == 0 { return CoinFlip::Heads; } else { return CoinFlip::Tails; } } fn main() { println!("You got: {:?}", flip_coin()); }
关键点:
- 枚举允许你从一种类型下收集一组值
- This page offers an enum type
CoinFlip
with two variantsHeads
andTails
. You might note the namespace when using variants. - 这可能是比较结构体和枚举的好时机:
- 在这两者中,你可以获得一个不含字段的简单版本(单位结构体),或一个包含不同类型字段的版本(变体载荷)。
- 在这两者中,关联的函数都在
impl
块中定义。 - 你甚至可以使用单独的结构体实现枚举的不同变体,但这样一来,如果它们都已在枚举中定义,类型与之前也不一样。