Enum
Enums allow you to have a set of named values, behaving similarly to enums in languages like TypeScript. You can define an enum using the enum keyword and a label, which will become the type name.
enum Status {
Pending,
Complete,
Failed,
}
You can access enum members with <enum>.<member>. You can then use this in your code:
fn checkStatus(Status st) -> str {
if st {
Status.Pending -> { return "pending" }
Status.Complete -> { return "complete" }
Status.Failed -> { return "failed" }
}
}
fn didFail(Status st) -> bool {
return st == Status.Failed
}
Status stat1 = Status.Complete
Status stat2 = Status.Failed
print(checkStatus(stat1)) // complete
print("{didFail(stat2)}") // true
Enums allow you to define different states of an object. For example, if you were making Conway's Game of Life, you may want to encode the cell state using an enum instead of a boolean, for clarity:
enum CellState {
Alive,
Dead,
}
You would then use this in your code:
mut CellState[][] board = [[...]]
for row in board {
for col in board[row] {
CellState north = board[row-1][col]
CellState northeast = board[row-1][col+1]
CellState east = board[row][col+1]/
// ...
mut int aliveNeighbors = 0
if north {
CellState.Alive -> { aliveNeighbors += 1 }
_ -> {}
}
if northeast {
CellState.Alive -> { aliveNeighbors += 1 }
_ -> {}
}
// ...
if aliveNeighbors {
$:1 -> { board[row][col] = CellState.Dead }
4:$ -> { board[row][col] = CellState.Dead }
3 -> { board[row][col] = CellState.Alive }
_ -> {}
}
}
}
Enum members can also contain values inside them. You can declare what the values are using the type. For instance:
struct Element {
str tagName,
[str]str attributes,
Node[] children
}
enum Node {
Root(Node[]),
Doctype,
Element(Element),
Comment(str),
Text(str)
}
You can get these values out by pattern matching on the type:
fn render(Node node) -> str {
return if node {
Node.Root(nodes) -> {
mut str out = ""
for node in nodes {
out = out <> render(node)
}
out
}
Node.Doctype -> { "<!doctype html>" }
Node.Element(el) -> { render(el) } // fn render(Element el) -> str
Node.Comment(comment) -> { "<!--" <> comment <> "-->" }
Node.Text(text) -> { text }
}
}