Working with Enums
Level: intro (score: 1)
🎯 In Python, you might use strings, integers, or even the built-in enum.Enum
to represent fixed states.
In Rust, enums go further: they can define variants and store data inside those variants.
For now, we’ll start with the simpler case — basic variants without extra data.
✅ Your task:
Implement the TrafficLight
enum with the following variants:
Red
Yellow
Green
Then implement the function action(light: TrafficLight) -> &'static str
which returns:
"stop"
forRed
"slow down"
forYellow
"go"
forGreen
This exercise introduces:
- Defining enums in Rust
- Matching on enum variants
- Returning string slices with a
'static
lifetime (&'static str
means the string is stored in the binary for the program’s entire lifetime — similar to how Python string literals live for the duration of the program)
🧠 Tip: use the match
expression to handle each enum variant explicitly. Rust will even warn you if you forget to handle one!