Skip to content
Draft

Enums

Enums define a type with a fixed set of named values.

enum Color
Red
Green
Blue
fin enum.
@primary = Color#Red

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)

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.53975

Bit flag enums:

flag enum Permissions
Read = 0x01
Write = 0x02
Execute = 0x04
fin enum.
@perms = Permissions#Read | Permissions#Write

Iterate over all enum values:

for @color in Color#values()
write(@color#name)
fin for.

Parse enum from string:

@color = Color#from_string("Red")

The built-in Result type is an enum:

enum Result<T, E>
ok(value: T)
err(error: E)
fin enum.

The built-in Option type:

enum Option<T>
some(value: T)
none
fin enum.

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.

pub enum Status
Active
Inactive
Pending
fin enum.
enum Either<L, R>
left(value: L)
right(value: R)
fin enum.
@result = Either<String, Int>#left("error")
@json = @shape#to_json()
@shape = Shape#from_json(@json)

Learn about Collections for arrays, maps, and sets.