The Rust Programming Language — Pattern Matching — Enums
enum or more elaborately known as Enumerations, are a group of possible set of values that can be assigned to a variable. Defining a set of values reduces chances of errors of accidentally assigning a wrong value.
Let’s say we want to restrict the types of colours a user can chose from Red,` Green, Yellow. Rust allows us to encode these possibilities as enums. Please check below snippet.
enum Color {
Red,
Yellow,
Green
}
fn main() {
let go = Color::Green;
let caution = Color::Yellow;
let stop = Color::Red;
}Observations:
- You need to use
enumkeyword to define an enum - You need to give it a name, in our case
Color. - In order to access values to be assigned to a variable, we need to access them using the namespace with double-colons
::. The namespace is the name of enum that we game which isColor. For e.g.Color::Green,Color::YelloworColor::Red.
In this case, Color is known as identifier and Red, Yellow and Green are known as variants. The identifier Color can be used as a type of variable. For e.g. refer to below snippet, the type of go, caution and stop is Color:
enum Color {
Red,
Yellow,
Green
}
fn main() {
let go: Color = Color::Green;
let caution: Color = Color::Yellow;
let stop: Color = Color::Red;
}An enum can contain a tuple as a variant as well as a struct.
Refer to below snippet for an example of tuple as a variant in an enum:
enum Color {
Red,
Yellow,
Green,
Custom(u8, u8, u8)
}
fn main() {
let go: Color = Color::Green;
let caution: Color = Color::Yellow;
let stop: Color = Color::Red;
let brown = Color::Custom(128, 64, 0);
}Observations:
- You can define a Custom
tupleas avariantin theenum. Custom(u8, u8, u8)is a type added in theColorenum.- You can assign a
Custom(u8, u8, u8)value to a variablebrownusing thenamespaceconcept.
Below is an example of how to use structs as a variants in the enum.
enum Color {
Red,
Yellow,
Green,
Custom { red: u8, green: u8, blue: u8 }
}
fn main() {
let go: Color = Color::Green;
let caution: Color = Color::Yellow;
let stop: Color = Color::Red;
let purple = Color::Custom { red: 128, green: 0, blue: 128 };
}Observations:
- Just like
tupleswe can define astructvariant Custom { red: u8, green: u8, blue: u8 }
I hope you liked this articles on how to create enum in Rust. Please leave your feedback in the comments section.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.
Stackademic
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Follow us on Twitter(X), LinkedIn, and YouTube.
- Visit Stackademic.com to find out more about how we are democratizing free programming education around the world.






