Skip to main content

Match

match chooses one branch out of many by a value. Unlike a chain of ifs, it jumps straight to the right branch. It works over integers and enums, and else catches whatever no other branch names:

let number = 2
let name = match(number) {
1 -> "one"
2 -> "two"
else -> "many"
}

A branch can run statements rather than give a value:

enum People { Teacher, Student, Unnamed }

let greet(person: People) {
match(person) {
People.Teacher -> println("Good morning, teacher")
People.Student -> println("Hi")
else -> println("Hello")
}
}

match!​

match! makes the compiler check that every case is handled, so it takes no else. If you add a case to the enum later, every match! over it stops compiling until it handles the new case:

enum Color { Red, Green }

let name(color: Color) = match!(color) {
Color.Red -> "red"
Color.Green -> "green"
}

Two branches can't name the same case. Matching over strings or floats is not in V0: compare them with if.