Defining Enums in Rust
Defining Enums
52
In Rust, an enum, short for "enumeration", is a custom data type that represents a set of possible values or variants. Enums are useful for representing a fixed set of options or states.
To define an enum in Rust, you use the enum
keyword followed by the name of the enum and a list of variants enclosed in curly braces.
For example, here is an enum representing different types of animals:
enum Animal { Dog, Cat, Bird, Fish, }
In this enum, Animal
is the name of the enum and it has four variants: Dog
, Cat
, Bird
, and Fish
.
You can create a variable of type Animal
by specifying one of these variants, like so:
let my_pet = Animal::Cat;
You can also attach data to each variant of an enum.
For example, if you wanted to represent different colors of cars, you could define an enum like this:
enum CarColor { Red, Blue, Green, Custom(String), }
In this enum, the Custom
variant includes an associated String
value to represent a custom color.
To create a variable of type CarColor
with the Custom
variant and a custom color value, you would specify it like this:
let my_car_color = CarColor::Custom("purple".to_string());
Enums are a powerful tool in Rust for representing fixed sets of options or states, and can be used in many different contexts.
March 27, 2023