Enum
Sometimes we want to call a function with a small selection of known arguments. Only a known value can be specified—we can use an enum
here.
With enums, we provide a set of names. An enum
variable can be created with any of the names. In Rust, each name can have an optional type—the name can have attached data of that type.
To start, we use a classic Animal enum
with the names Bird, Frog and Cat. So any Animal enum
variable can be one of those names.
string
based on the value of the enum
local variable.enum Animal { Bird, Frog, Cat } fn main() { let animal = Animal::Frog; // Match the enum. let result = match animal { Animal::Bird | Animal::Frog => "Bird or frog", _ => "Other" }; println!("ENUM RESULT: {}", result); }ENUM RESULT: Bird or frog
Enums have a more powerful syntax in Rust than in many languages. For each name in an enum
, we can specify an attached type. For example, here the Name has a String
.
enum
, we must specify a valid String
as well.string
that is attached to a Name. We can capture the string
in a match expression.// Use enum with data types. enum Info { Name(String), Index(usize) } fn main() { let info = Info::Name("Test".to_string()); match info { Info::Name(c) => println!("Name = {}", c), _ => println!("No name") } }Name = Test
Sometimes we have a simple group of constants and want each one to have a number like 0, 1, 2 and further. These are implicit value enums.
usize
.enum AnimalType { Bird, Rat, Mouse, } fn main() { // Use implicit values from unit-only enums. let animal = AnimalType::Bird; let animal_value = animal as usize; println!("BIRD = {}", animal_value); let animal = AnimalType::Rat; let animal_value = animal as usize; println!("RAT = {}", animal_value); }BIRD = 0 RAT = 1
With unit-only enums, we can assign a value that can later be accessed in the Rust program through casting. This gives us a way to use enums for a collection of constant values.
enum ImportantInfo { Top = 100, Medium = 50, Low = 10, } fn main() { let x = ImportantInfo::Medium; println!("MEDIUM = {}", x as usize); }MEDIUM = 50
Enums enhance the type system in Rust. We can do everything we need without enums—but enums involve the type system and can make programs more resilient to change.
We used enums to specify a selection of values in programs. This allows us to verify programs with types, even when we just are using values.