Enums
Enums define a type with a fixed set of named values.
Basic Enums
Section titled “Basic Enums”enum Color Red Green Bluefin enum.
@primary = Color#RedEnums with Values
Section titled “Enums with Values”Enums can carry associated data:
enum Shape Circle(radius: Float) Rectangle(width: Float, height: Float) Triangle(base: Float, height: Float)fin enum.
@circle = Shape#Circle(radius: 5.0)@rect = Shape#Rectangle(width: 10.0, height: 20.0)Enum Actions
Section titled “Enum Actions”Define actions on enums:
enum Shape Circle(radius: Float) Rectangle(width: Float, height: Float)fin enum.
impl Shape action area(@self: Shape) -> Float match @self when Circle then return 3.14159 * @self#radius * @self#radius when Rectangle then return @self#width * @self#height fin match. fin action.fin impl.
@circle = Shape#Circle(radius: 5.0)write(@circle#area()) @// 78.53975Enum with Flags
Section titled “Enum with Flags”Bit flag enums:
flag enum Permissions Read = 0x01 Write = 0x02 Execute = 0x04fin enum.
@perms = Permissions#Read | Permissions#WriteEnum Iteration
Section titled “Enum Iteration”Iterate over all enum values:
for @color in Color#values() write(@color#name)fin for.Enum from String
Section titled “Enum from String”Parse enum from string:
@color = Color#from_string("Red")Result Enum
Section titled “Result Enum”The built-in Result type is an enum:
enum Result<T, E> ok(value: T) err(error: E)fin enum.Option Enum
Section titled “Option Enum”The built-in Option type:
enum Option<T> some(value: T) nonefin enum.Exhaustive Matching
Section titled “Exhaustive Matching”Match must handle all enum variants:
match @shape when Circle then handle_circle(@shape) when Rectangle then handle_rect(@shape) when Triangle then handle_triangle(@shape)fin match.Missing a variant is a compile error.
Enum Visibility
Section titled “Enum Visibility”pub enum Status Active Inactive Pendingfin enum.Generic Enums
Section titled “Generic Enums”enum Either<L, R> left(value: L) right(value: R)fin enum.
@result = Either<String, Int>#left("error")Enum Serialization
Section titled “Enum Serialization”@json = @shape#to_json()@shape = Shape#from_json(@json)Next Steps
Section titled “Next Steps”Learn about Collections for arrays, maps, and sets.
