Enums
- An enum defines a closed set of variants under one nominal type.
- Unit variants carry no data; structured variants carry named typed fields.
- Construct values with Enum.Variant or Enum.Variant { fields }.
Defining An Enum
1enum ExpenseStatus {2 Draft,3 Open,4 Submitted,5 Approved { approved_at: time },6 Rejected { reason: string },7 Settled8}The enum name and variant names use PascalCase. Unit variants end after their name. Structured variants declare fields inside braces. Both forms may appear in the same enum.
Constructing Variant Values
1ExpenseStatus fn approvalStatus(bool approved, time approved_at) {2 if approved {3 return ExpenseStatus.Approved { approved_at }4 }56 return ExpenseStatus.Rejected {7 reason: "Receipt is missing"8 }9}A unit variant is a complete value after Enum.Variant. A structured variant needs braces containing every required field with a compatible value.
Enums Are Nominal
1enum ExpenseDecision {2 Approved { approved_at: time }3}45enum SettlementDecision {6 Approved { approved_at: time }7}89fn invalidStatusAssignment(time approved_at) {10 SettlementDecision decision = ExpenseDecision.Approved {11 approved_at12 }13}The two Approved variants have the same field shape but remain different types. Enum identity includes the enum name; structural compatibility does not merge enums. These deliberately separate decision enums leave the guide’s canonical ExpenseStatus definition unchanged.
Defaulting A Structured Variant
1default ExpenseStatus.Rejected {2 reason: "No reason supplied"3}A default block may supply fields for one structured variant. The target and fields must exist, values must match, and the same target may have only one default block.
When To Use An Enum
| Situation | Choose |
|---|---|
| A fixed set of known states | Enum. |
| Each state may carry different typed data | Structured enum variants. |
| Open-ended free text | string. |
| Several independent booleans may all be true | Separate bool fields. |
| The value needs durable record identity | An entity, possibly containing an enum field. |
Common Mistakes
| Wrong | Correct |
|---|---|
Bare Approved | ExpenseStatus.Approved |
| Use a structured variant without its fields | Construct it with braces and required fields. |
| Treat equal-looking variants as compatible | Keep the enum name in the type contract. |
| Use switch/case | Use match/to. |
