Control flow
if/elif/else, while, for, loop, break/continue, labeled loops, and break-with-value.
Summary
Braces are always required. if is an expression and returns the taken branch value. for iterates over arrays, ranges, strings, and maps (yielding key-value tuples when destructured). loop runs forever until break; break val makes the loop expression return that value. Labeled loops let you break outer or continue outer from a nested loop.
Canonical
If / Elif / Else
if x > 0 {
println("positive")
} elif x < 0 {
println("negative")
} else {
println("zero")
}Braces are always required.
if works as an expression: it returns the value of the taken branch:
let sign = if x > 0 { "+" } else { "-" }While Loop
var i = 0
while i < 10 {
println(i)
i = i + 1
}For Loop
-- over array
for x in [1, 2, 3] {
println(x)
}
-- over range (exclusive)
for i in 0..5 {
println(i) -- 0, 1, 2, 3, 4
}
-- over range (inclusive)
for i in 1..=3 {
println(i) -- 1, 2, 3
}
-- over string characters
for ch in "hello".chars() {
print(ch)
}
-- over map (iterates keys)
let m = #{"a": 1, "b": 2}
for k in m {
println("{k}: {m[k]}")
}
-- over map key-value pairs (direct destructuring)
for (k, v) in m {
println("{k} = {v}")
}
-- .entries() also works
for (k, v) in m.entries() {
println("{k} = {v}")
}Loop (Infinite)
var n = 0
loop {
n = n + 1
if n >= 10 { break }
}Break and Continue
for i in 0..100 {
if i % 2 == 0 { continue } -- skip even numbers
if i > 20 { break } -- stop at 20
println(i)
}Break with Value
loop can return a value via break:
let result = loop {
break 42
}
println(result) -- 42Labeled Loops
Break or continue an outer loop from an inner one.
outer: for i in range(5) {
for j in range(5) {
if i * j == 6 {
break outer -- breaks the outer loop
}
}
}
outer2: for i in range(3) {
for j in range(3) {
if j == 1 { continue outer2 } -- skips to next i
}
}