Working with Enums
Level: intro (score: 1)
🚀 These intro exercises are prep for our
Rust Intro Cohort Program.
🎯 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!
pub enum TrafficLight {
// define the variants here
}
pub fn action(light: TrafficLight) -> &'static str {
// match on `light` and return the right string
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_red_light() {
assert_eq!(action(TrafficLight::Red), "stop");
}
#[test]
fn test_yellow_light() {
assert_eq!(action(TrafficLight::Yellow), "slow down");
}
#[test]
fn test_green_light() {
assert_eq!(action(TrafficLight::Green), "go");
}
}