Contents

Conditions are bool. Pattern matching is the only way to inspect a sum value.

Conditionals#

An if tests a boolean expression. A block body is enclosed in braces; a single indented statement is also accepted.

fn classify(n i32) str {
    if n < 0 {
        return "negative"
    } else if n == 0 {
        return "zero"
    } else {
        return "positive"
    }
}

When both branches produce a value, the if is an expression whose type is the common type of the branches. Without an else, it is a statement and produces void.

const parity = if n % 2 == 0 { "even" } else { "odd" }

The condition must be bool. There is no implicit truthiness.

For-In Loops#

for name in list visits each element in order. The loop variable is scoped to the body.

fn total(xs List[i32]) i32 {
    var sum = 0
    for x in xs {
        sum += x
    }
    return sum
}

The expression after in must be a list. Strings are not iterable as runes; see Strings, Bytes, and Runes. The loop variable is a copy for scalar element types and a reference for managed element types.

Range Loops#

for name in lo..hi visits integers from lo inclusive to hi exclusive. Both bounds are evaluated once before the loop. The loop variable type follows the wider bound, with i32 as the default.

fn sum_to(n i32) i32 {
    var total = 0
    for i in 0..n {
        total += i
    }
    return total
}

A descending range is not expressed by reversing the bounds.

Condition Loops#

for condition is a while loop. The condition is evaluated before each iteration. A bare for is an infinite loop equivalent to for true.

fn count_down(n i32) {
    var i = n
    for i > 0 {
        print(i)
        i -= 1
    }
}

fn forever() {
    for {
        if should_stop() {
            break
        }
    }
}

Loop Invariants#

All loop forms accept : invariant clauses between the header and the body. The invariant is a boolean predicate over the loop variable and values in scope. It is checked before the loop condition on every iteration, including before the first.

fn save(account Account, amount i64, months i64) Account
    : pre months >= 0
{
    var acc = account
    for i in 0..months
        : invariant acc.balance == account.balance + amount * i
    {
        acc = deposit(acc, amount)
    }
    return acc
}

A constant invariant that is false is rejected during compilation. Other invariants become runtime checks unless the program is built with -release. See Loop Invariants.

Break and Continue#

break exits the nearest enclosing loop. continue skips the rest of the current iteration. Both are statements.

for x in xs {
    if x < 0 {
        continue
    }
    if x > limit {
        break
    }
    print(x)
}

break or continue outside a loop is rejected. Inside a defer body, they may only target a loop inside that defer. See Defer.

Matching#

match inspects a sum type, enum, Option, or Result. Each arm names a constructor and binds its fields. A wildcard arm uses _.

type Shape =
    | Circle(radius f64)
    | Rect(width f64, height f64)

fn area(shape Shape) f64 => match shape {
    Circle(radius) => 3.14159 * radius * radius
    Rect(width, height) => width * height
}

An enum pattern is qualified with the enum type, as in Color.Red. A sum type pattern uses the variant name directly. Bindings in an arm are immutable.

type Color enum {
    Red
    Green
    Blue
}

fn code(colour Color) i32 => match colour {
    Color.Red => 1
    Color.Green => 2
    Color.Blue => 3
}

A match must be exhaustive. The compiler rejects a match that leaves a variant unhandled.

If-Let Tests#

is tests a value against a pattern and produces bool. In an if condition, bindings introduced by the pattern are visible in the then branch.

if response is Success(value) {
    print(value)
} else {
    print("request failed")
}

if n is Positive(p) {
    print(p)
}

The else branch does not receive the bindings. If both outcomes need values, use match. For a refinement, is also checks the invariant at runtime.

Return#

return exits the current function and optionally supplies a value. A function with a non-void return type must return a value on every path, or leave a final expression of a compatible type in a block body.

fn sign(n i32) i32 {
    if n < 0 {
        return -1
    } else if n > 0 {
        return 1
    }
    return 0
}

fn double(n i32) i32 {
    n * 2
}

Blocks#

Braces introduce a scope. A block in expression position produces the value of its final expression.

const total = {
    const a = 10
    const b = 20
    a + b
}

defer is scoped to the block in which it is registered. Each loop iteration creates a fresh body scope. See Defer.