Enums: One of a Few
Look at a traffic light. π¦ It is always exactly one color β red, or yellow, or green. It can never be all of them at once. Rust has a handy tool for βpick one from a small listβ and itβs called an enum.
Building a traffic light
Letβs make an enum for our traffic light. Each choice is called a variant.
enum Light {
Red,
Yellow,
Green,
}
Now we can make a value. We pick a variant with two dots, like Light::Red.
Red,
Yellow, and Green are the three variants of Light.
Using an enum value
Here we make a light and print a friendly message. We use a tiny match to peek at which
variant we have β youβll learn all about match in the next lesson. π©
Light::Green to
Light::Red and run it again. The message changes all by itself! π¦
A famous enum: Option
Rust has a built-in enum called Option that means βmaybe thereβs a value, or maybe
thereβs nothing.β It has two variants:
Some(value)β yes, hereβs a value! πNoneβ nope, empty. π³οΈ
So instead of an unexpected βnothing hereβ surprise, Rust makes you say it out loud. That keeps your programs safe.
Light::Yellow
print? Switch the value and check if you guessed right!
Quick quiz
How many variants can one enum value be at the same time?
Right! An enum value is exactly one of its choices β just like a traffic light shows one color at a time. π¦
Light::Red. You also met Option
with its Some and None. Next up: match: The Sorting
Hat β a clean way to do different things for each variant. π©