Switch

Allows matching a single value with many values.

Literals

switch (x)
case 0 {
    print("got 0")
}
case 1 {
    print("got 1")
}
else {
    print("got a number")
}

Variable bind

switch (thing)
case x {
    // do stuff with x
}

Tuples

val data = #("John", 32)

switch (data)
case #("John", age) {
    // match on John, get age
}
case #(name, 32) {
    // match on age 32, get name
}
case #(name, age) {
    // match on any
}

Union

With unions:

type Result = union {
    Created(String),
    NoContent,
    NotFound,
    Error(String),
}

val result: Result = get_data()

switch (result)
case Result.Created(data) {
    // do stuff with data...
}
case .Error(reason) {
    // do stuff with the reason
}
else {
    // others
}

Structs

type Person = struct {
    name: String,
    age: u64,
}

var person = get_person()

switch (person)
case Person{ name = "John", age } {
    // match on "John" with explicit type
}
case .{ name = "Jane", age } {
    // match on "Jane", infer struct type
}
case .{ age = 32 } {
    // match on age, ignore others
}

Guards

swith (person)
case #("John", age) if age < 18 {
    // match on "John" and age<18 ...
}
case #("John", age) {
    // all other ages ...
}

Others

Nullables: use if (maybe_data) |data| { ... } instead.

Errors: use try/catch instead.