Control flow and data
Everything on this page is in one script that sub check accepts and sub run prints the output of (shown at the end).
Loops and ranges
Section titled “Loops and ranges”let mut total = 0for (i in 0..5) { if (i == 3) { continue } total += i}
let mut n = 10while (n > 0) { n -= 3 if (n < 4) { break }}0..5 stops before 5; 0..=5 includes it. continue and break work in for and while. += and -= change a let mut value.
Destructuring
Section titled “Destructuring”let (a, b) = (1, 2)let [first, second] = [10, 20]let { name, port } = { name: "sub", port: 8080 }Tuples, lists and records can be taken apart in let, for and match.
match: patterns and guards
Section titled “match: patterns and guards”fn classify(n) { match (n) { 0 => "zero", x if x < 0 => "negative", 1..=9 => "small", _ => "big" }}A pattern can be a literal, a range, a name, a constructor or _. pattern if condition => is a guard. match must still cover every case.
if let
Section titled “if let”let maybe = find([1, 2, 3, 4, 5], fn(x) { x > 3 })if (let Some(v) = maybe) { print("found", v) }The condition stays in parentheses; let goes inside them.
Slices, maps, sets, defaults and formats
Section titled “Slices, maps, sets, defaults and formats”let xs = [1, 2, 3, 4, 5]print(xs[1..3]) // [2, 3]let m = #{ "a": 1, "b": 2 } // a maplet s = #[1, 2, 2, 3] // a set: #[1, 2, 3]let who = None ?? "anon" // ?? gives a defaultprint("{who:>8}|", 0xff, 1_000, 2e3) // a format spec, hex, underscores, exponentsprint(r"C:\raw\path") // a raw string?. reads a field of an Option only when there is one. Strings can be raw (r"...") or triple-quoted.
The whole script
Section titled “The whole script”let mut total = 0for (i in 0..5) { if (i == 3) { continue } total += i}print(total)
let mut n = 10while (n > 0) { n -= 3 if (n < 4) { break }}print(n)
let (a, b) = (1, 2)let [first, second] = [10, 20]let { name, port } = { name: "sub", port: 8080 }print(a + b, first + second, name, port)
fn classify(n) { match (n) { 0 => "zero", x if x < 0 => "negative", 1..=9 => "small", _ => "big" }}print(classify(0), classify(-4), classify(7), classify(100))
let xs = [1, 2, 3, 4, 5]print(xs[1..3])let m = #{ "a": 1, "b": 2 }let s = #[1, 2, 2, 3]print(m, s)
let maybe = find(xs, fn(x) { x > 3 })if (let Some(v) = maybe) { print("found", v) }let name2 = None ?? "anon"print("{name2:>8}|", 0xff, 1_000, 2e3)print(r"C:\raw\path")713 30 sub 8080zero negative small big[2, 3]{a: 1, b: 2} #[1, 2, 3]found 4 anon| 255 1000 2000.0C:\raw\path