🚦
World 6 Β· Choices & Magic Sorting

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.

The Big Idea An enum is a type whose value is exactly one of a few named choices. We list every possible choice, and a value must be one of them β€” never two, never none-of-them.

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.

New word A variant is one of the choices inside an enum. Red, Yellow, and Green are the three variants of Light.
Think of it like this… An enum is like a music playlist set to "single track" β€” at any moment exactly one song is playing. You can switch which one, but you can't play "red and green" at the same time.

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. 🎩

Ferris says: Try changing 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.

Try this! In the code box above, add a fourth line of thinking: what would 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. 🚦

You learned… An enum lets a value be exactly one of a few named variants, like 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. 🎩