Curriculum Data modeling Enums as tagged unions
Enums as tagged unions
Rust enums are real sum types: each variant can carry different data. This is the closest Rust analogue to TypeScript discriminated unions, but the compiler enforces exhaustiveness. Planned exercises: 1. choose enum syntax. 2. recognise tuple-like and struct-like variants. 3. choose an enum over string tags. 4. fill a variant constructor. 5. fill an enum type annotation. 6. write a small enum. 7. write a value of a data-carrying variant. 8. translate a TS discriminated union. 9. model a small state machine with enum variants.
Exercises
9 ready
01
pick one
Declare a TrafficLight with three states (Red, Yellow, Green).
02
pick one
An enum's variants can carry payload — positional, named, or none.
03
pick one
A function accepts a "kind" parameter from a small fixed set:
04
fill blanks
Fill the variant name. job should be the unit-variant for a
05
fill blanks
Fill the type annotation. light is one of the three
06
write a program
Define an enum Color with three unit variants Red, Green,
07
write a program
Define an enum Message with two variants: Quit (unit) and
08
write a program
Translate the TS discriminated union to Rust. Outcome::Ok(i32)
09
write a program
Model a small Door state machine as an enum. Variants: