Match has similar synax to switch, but match works on types instead of values. When combining match with functions we can get powerful multiple return types from functions and error checking.
use fmt;
fn check(in: int) (int | str | void) = {
if (in > 0 && in < 10) {
return in;
} else if (in < 0) {
return "it is negative";
} else {
return;
};
};
export fn main() void = {
// Define a tagged union age of either u32 or u64, but assign it
// 43 as a u32.
let age: (u32 | u64) = 43u32;
// Matching on age gets us a u32 of value 43.
match (age) {
case u32 =>
fmt::println("age is a u32")!;
case =>
fmt::println("age is something else")!;
};
// Matching on the result of the function lets us branch into
// different paths.
match (check(5)) {
case int =>
fmt::println("We got an int back")!;
case str =>
fmt::println("We got a str back")!;
case void =>
fmt::println("We got nada back")!;
};
// We can even get the value of the matched type back inside our
// branch to use it!
match (check(-3)) {
case let i: int =>
fmt::println("We got an int back", i)!;
case let s: str =>
fmt::println("We got a str back", s)!;
case void =>
fmt::println("We got nada back")!;
};
};
$ hare run match.ha
4/4 tasks completed (100%)
age is a u32
We got an int back
We got a str back it is negative
Back to table of contents