Control flow

if / else if / else

if x > 10 {
    println("big")
} else if x > 5 {
    println("medium")
} else {
    println("small")
}

Parentheses around the condition are optional. Conditions use the comparison (==, !=, <, <=, >, >=) and logical (&&, ||, !) operators, which short-circuit.

while

let i = 0
while i < 10 {
    println(i)
    i += 1
}

An infinite loop is just while true { ... }.

for..in

Iterate over the elements of an array:

let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
    println(fruit)
}

Iterate over a range of integers with the built-in range:

for i in range(5) {        // 0,1,2,3,4
    println(i)
}

for i in range(2, 7) {     // 2,3,4,5,6
    println(i)
}

Iterating objects & custom iterators

for..in also works on objects. If a value has an iter() method, it’s called once to get an iterator, then the iterator’s next() is called each round. next() returns {value, done} (or nil when exhausted):

class Range {
    fn iter() {
        return Range{n: self.start, end: self.end}
    }
    fn next() {
        if self.n >= self.end {
            return nil               // done
        }
        let v = self.n
        self.n += 1
        return {value: v, done: false}
    }
}

for x in Range{start: 0, end: 3} {
    println(x)                       // 0, 1, 2
}

A plain object without iter() falls back to iterating its keys in sorted order.

break and continue

break exits the nearest enclosing loop; continue skips to its next iteration. Both work in while and for..in loops:

for n in range(100) {
    if n % 2 == 1 {
        continue          // skip odd numbers
    }
    if n > 10 {
        break             // stop once past 10
    }
    println(n)            // 0, 2, 4, 6, 8, 10
}

Notes

  • There is no switch/case; use an if / else if chain.
  • There is no C-style for (init; cond; step) loop — only while and for..in.
  • For recoverable failures, see error handling (try / catch / throw).

Next: arrays.