Guides · 05

Control flow

This guide covers how a Vyi program chooses what to run and how often: if, switch, match, the for loop, labels, and blocks that produce values. It ends with a short look at defer.

Two ideas run through all of it:

  • if, switch, match, and a bare { } block can each produce a value, so choosing between values rarely needs a mut binding.
  • for is the only loop. It covers what other languages split into while, for-each, and infinite loops.

if

An if needs no parentheses around its condition, and its body always goes in braces, even when it's one statement. Add else if and else branches as needed:

Vyi
import { println } from "@fmt"

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

fn main() !u8 {
    println(sign(-7))   // prints -1
    return Ok(0)
}

The condition must be a bool. An integer is not a boolean: write if count != 0, not if count.

if as an expression

Written where a value is expected, if is an expression. Each branch's block gives the value of its last expression, and the if takes the value of the branch that runs:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con score = 72
    con result = if score >= 50 { "pass" } else { "fail" }
    con grade = if score >= 90 { "A" }
        else if score >= 70 { "B" }
        else { "C" }
    println(result)   // prints pass
    println(grade)    // prints B
    return Ok(0)
}

An if expression needs an else, because without one there is no value when the condition is false:

Vyi · does not compile
fn clamp(n: i32) i32 {
    return if n > 0 { n }   // error: requires an else
}

fn main() !u8 { return Ok(0) }

The exception is a condition the compiler can work out before the program runs, a known value. if true { 1 } is always 1, so it needs no else. A known-false condition without an else has no value and is still an error. Guide 11 covers known values.

A branch can leave instead of giving a value: it can end in return, break, continue, or panic. The if then takes its value from the branches that do give one. This works anywhere an if appears, even in the middle of an expression:

Vyi
import { println } from "@fmt"

fn result(score: i32) [*con]u8 {
    con points = if score >= 0 { score }
        else { return "invalid" }
    return if points >= 50 { "pass" } else { "fail" }
}

fn main() !u8 {
    println(result(70))   // prints pass
    println(result(-5))   // prints invalid
    return Ok(0)
}

For a score below zero, the else branch returns from result, and points is never bound. Otherwise points takes the value of the first branch.

switch

Vyi has two ways to pick one of several branches. switch chooses by value: each arm is an expression, compared with the subject using ==. match chooses by shape: each arm names an enum variant or a type (below). Both are written as the keyword, the subject, then a { } list of arms, each arm: body. A body is one expression or statement. A body of several statements goes in its own { } block.

A switch arm can be any expression of the subject's type: a literal, a binding, or a call. Several values separated by commas share one arm, and the arm named default catches everything else:

Vyi
import { println } from "@fmt"

fn busyCode() i32 { return 503 }

fn describe(code: i32) [*con]u8 {
    con notFound = 404
    return switch code {
        200:        "ok",          // a literal
        notFound:   "not found",   // a binding
        busyCode(): "busy",        // a call
        301, 302:   "moved",       // either value
        default:    "unknown",
    }
}

fn main() !u8 {
    println(describe(200))   // prints ok
    println(describe(404))   // prints not found
    println(describe(503))   // prints busy
    println(describe(302))   // prints moved
    return Ok(0)
}

The subject is evaluated once. Arms are tried from top to bottom, and an arm's expression is evaluated only if every arm above it failed to match. So busyCode() runs at most once per switch, and not at all when code is

  1. default may appear only once, and it must be the last arm.

Anything that supports == can be a subject, strings included:

Vyi
import { println } from "@fmt"

fn daysIn(month: [*con]u8) i32 {
    return switch month {
        "feb":   28,
        "apr", "jun", "sep", "nov": 30,
        default: 31,
    }
}

fn main() !u8 {
    println(daysIn("feb"))   // prints 28
    println(daysIn("jun"))   // prints 30
    return Ok(0)
}

A struct can be a subject once you define an @eq method for it (guide 13).

Range arms

When the subject is a number or a char, an arm can be a range. The arm matches when the subject lies inside it. lo..hi stops before hi, lo...hi includes hi, and a range with one end left out has no limit on that side:

Vyi
import { println } from "@fmt"

fn grade(score: i32) [*con]u8 {
    return switch score {
        ..0:      "invalid",   // below 0
        0..50:    "fail",      // 0 to 49
        50...100: "pass",      // 50 to 100
        101..:    "invalid",   // 101 and up
    }
}

fn main() !u8 {
    println(grade(49))    // prints fail
    println(grade(100))   // prints pass
    return Ok(0)
}

A range held in a binding works as an arm too, and its ends can be values computed while the program runs.

Covering every case

grade has no default arm and needs none, because its arms cover every i32. Every switch must either have a default arm or have an arm for every value its subject can take. The compiler can check the second only for arms that are known values (literals, for example), and only for subjects with a countable set of values:

  • a bool: true and false
  • an enum whose variants carry no data: every variant
  • a union of single values, such as "fast" | "slow": every member
  • an integer or a char: values and ranges that together span the whole type, as in grade
Vyi
import { println } from "@fmt"

enum Light { Red, Yellow, Green }

fn action(l: Light) [*con]u8 {
    return switch l {
        Red:          "stop",
        Light.Yellow: "slow",
        Green:        "go",
    }
}

fn main() !u8 {
    con isOpen = true
    con sign = switch isOpen { true: "open", false: "closed" }
    println(action(Yellow))   // prints slow
    println(sign)             // prints open
    return Ok(0)
}

As guide 03 showed, an arm can name a variant bare (Red) or with its enum (Light.Yellow).

Any other subject, such as a string or a float, needs a default arm, and so does a switch whose arms are bindings or calls. A switch that leaves cases open is an error, and the message names the missing cases. For an integer subject it lists them as ranges.

Vyi · does not compile
enum Light { Red, Yellow, Green }

fn action(l: Light) [*con]u8 {
    return switch l {   // error: missing Green
        Red:    "stop",
        Yellow: "slow",
    }
}

fn main() !u8 { return Ok(0) }

The compiler also rejects an arm that can never match because known arms above it already cover it, such as the same value twice or a value inside an earlier range:

Vyi · does not compile
fn grade(score: i32) [*con]u8 {
    return switch score {
        50...100: "pass",
        75:       "good",   // error: can never match
        default:  "fail",
    }
}

fn main() !u8 { return Ok(0) }

Arms that overlap only in part are allowed. The first one that matches wins.

Guard chains

To pick a branch by condition rather than by value, switch over true and make each arm a condition. The arms are tried in order:

Vyi
import { println } from "@fmt"

fn shipping(weight: i32) i32 {
    return switch true {
        weight > 10: 100,
        weight > 5:  50,
        default:     0,
    }
}

fn main() !u8 {
    println(shipping(7))   // prints 50
    return Ok(0)
}

Nothing here is special syntax. Each arm is a bool expression, compared with true like any other switch arm.

match

Guide 03 introduced match for taking an enum apart. Each arm names a variant, and parentheses after the name bind the variant's data to new names:

Vyi
import { println } from "@fmt"

enum Shape {
    Dot,
    Square(i32),
    Rect(i32, i32),
}

fn area(s: Shape) i32 {
    return match s {
        Dot:        0,
        Square(n):  n * n,
        Rect(w, h): w * h,
    }
}

fn main() !u8 {
    println(area(Rect(4, 5)))   // prints 20
    return Ok(0)
}

A name in a match arm always means a variant or a type, never a binding, even when a binding with that name is in scope. A match must handle every variant, so leaving one out is an error:

Vyi · does not compile
enum Light { Red, Yellow, Green }

fn action(l: Light) [*con]u8 {
    return match l {   // error: non-exhaustive match; missing Green
        Red:    "stop",
        Yellow: "slow",
    }
}

fn main() !u8 { return Ok(0) }

The catch-all arm is default, the same word as in switch, and it counts as handling every variant the other arms leave out. Neither _ nor else is a catch-all.

match and switch are reserved words. default is not: a binding, a function, or a variant can be named default. Only an arm written as the bare word default is the catch-all. To name something called default in an arm, put it in parentheses:

Vyi
import { println } from "@fmt"

enum Mode { default, fast, safe }

fn level(m: Mode) i32 {
    return match m {
        (default): 1,   // the variant
        fast:      2,
        default:   0,   // the catch-all
    }
}

fn main() !u8 {
    println(level(Mode.default))   // prints 1
    println(level(safe))           // prints 0
    return Ok(0)
}

Each construct refuses the other's job and tells you which one to use. An arm that binds data is a pattern, not a value, so it can't appear in a switch:

Vyi · does not compile
enum Shape { Dot, Square(i32) }

fn side(s: Shape) i32 {
    return switch s {
        Square(n): n,   // error: is a value
        default:   0,
    }
}

fn main() !u8 { return Ok(0) }

In the other direction, a match over a value with no variants, such as an i32, is rejected with "match selects by shape; i32 has none".

Matching on a union's type

A union value holds one of its member types (guide 03). match typeof picks an arm by which one it holds:

Vyi
import { println } from "@fmt"

fn kind(u: i32 | bool) [*con]u8 {
    return match typeof u {
        i32:  "number",
        bool: "flag",
    }
}

fn main() !u8 {
    println(kind(7))      // prints number
    println(kind(true))   // prints flag
    return Ok(0)
}

match patterns go further than this: nested patterns, values inside a pattern, and narrowing. Guide 06 covers them.

Rules shared by switch and match

Commas between arms

Arms are separated by commas, and one rule decides whether the last arm takes one too. It's the same rule that struct and enum declarations follow:

  • If a line break follows the {, every arm ends with a comma, the last one included.
  • If the first arm is on the same line as the {, commas go only between arms, with none after the last.
Vyi · does not compile
fn label(n: i32) i32 {
    switch n {
        1:       return 10,
        default: return 99
    }   // error: multi-line switch must end with a trailing `,`
}

fn main() !u8 { return Ok(0) }

So switch n { 1: 10, default: 99 } is correct on one line, and writing 99, } there is an error.

switch and match as expressions

Written where a value is expected, each arm gives a value, and an arm that is a single expression needs no braces:

Vyi
import { println } from "@fmt"

enum Light { Red, Yellow, Green }

fn main() !u8 {
    con coins = 2
    con word = switch coins { 1: "one", default: "many" }
    con light = Light.Green
    con canGo = match light { Green: true, default: false }
    println(word)    // prints many
    println(canGo)   // prints true
    return Ok(0)
}

As with if, an arm that leaves with return, break, or panic gives no value, and the expression takes its value from the arms that do.

Several values in one arm

Comma-separated values or variants before the : are alternatives that share one body. In a switch they're tried left to right:

Vyi
import { println } from "@fmt"

enum Light { Red, Yellow, Green }

fn mustStop(l: Light) bool {
    return match l {
        Red, Yellow: true,
        Green:       false,
    }
}

fn main() !u8 {
    con day = 6
    con weekend = switch day { 6, 7: true, default: false }
    println(mustStop(Yellow))   // prints true
    println(weekend)            // prints true
    return Ok(0)
}

In a match, an arm with alternatives can't bind data. A name bound by one alternative would have no value when another alternative matched, so an arm like Ok(n), Err(_): is an error.

Loops

for is the only loop keyword. It has three forms.

With a condition, it runs while the condition is true:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut count = 0
    for count < 3 {
        count += 1
    }
    println(count)   // prints 3
    return Ok(0)
}

With no condition, it runs until a break or return leaves it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut tries = 0
    for {
        tries += 1
        if tries == 3 { break }
    }
    println(tries)   // prints 3
    return Ok(0)
}

With for x in, it runs once for each item of a range, a fixed-size array [N]T, or an array pointer [*con]T. A string literal is a [*con]u8, so for walks its bytes. The loop variable is a new con binding on each pass, so the body can't assign to it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut total = 0
    for n in 1..4 { total += n }           // 1, 2, 3
    println(total)                         // prints 6

    con prices = [3]i32[10, 20, 30]
    mut sum = 0
    for price in prices { sum += price }
    println(sum)                           // prints 60

    mut letters = 0
    for byte in "hey" { letters += 1 }
    println(letters)                       // prints 3
    return Ok(0)
}

Your own types can be looped over too. for accepts a value whose type has an @iter() method returning an iterator, whose @next() method gives Some(item) for each item and then None. It also accepts a type with @index(i32) and length() methods. The built-in collections work this way (guide 10).

break leaves the innermost loop, and continue skips to its next pass:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut total = 0
    for n in 1..100 {
        if n == 3 { continue }   // skip 3
        if n == 5 { break }      // stop at 5
        total += n
    }
    println(total)   // prints 7
    return Ok(0)
}

The loop adds 1, 2, and 4. It skips 3 and never reaches 5.

Ranges and slicing

a..b is the range from a up to but not including b. a...b includes b:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut last = 0
    for n in 1..3 { last = n }
    println(last)   // prints 2
    for n in 1...3 { last = n }
    println(last)   // prints 3
    return Ok(0)
}

Each loop leaves the last number it reached in last: 2 for 1..3, and 3 for 1...3.

A range is an ordinary value with start and end fields. Indexing an array or a [*con]T with a range slices it: you get a view of part of the same storage, without a copy. Leave out the start to begin at the first element, or the end to run to the last:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con s = "hello"
    println(s[1..3])   // prints el
    println(s[..2])    // prints he
    println(s[3..])    // prints lo
    return Ok(0)
}

Write the range in the for itself, as in for x in 0..10. A range held in a binding can't be looped over.

Labels and jumps

Put #name before a loop to label it. break #name and continue #name then act on that loop from anywhere inside it, which is how you leave nested loops:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    mut checked = 0
    #rows for row in 0..3 {
        for col in 0..3 {
            checked += 1
            if row == 1 && col == 1 { break #rows }
        }
    }
    println(checked)   // prints 5
    return Ok(0)
}

The loops check three cells in row 0 and two in row 1. Then break #rows stops both loops, where a plain break would stop only the inner one and go on to row 2.

A label can only name a loop or block that encloses the jump. You can't jump into a sibling, and Vyi has no goto. A plain block can carry a label too, and break #name leaves it, but continue works only with loops.

Blocks that give a value

A bare { } block written where a value is expected gives the value of its last expression:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con total = {
        con price = 20
        con tax = 2
        price + tax
    }
    println(total)   // prints 22
    return Ok(0)
}

Inside such a block, break value leaves it early with that value. With a label, break #name value leaves the labeled block from anywhere inside it, including from inside a loop. That lets you write "search, and stop at the first hit" as one expression:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    con prices = [4]i32[5, 12, 30, 8]
    con firstOver10 = #search {
        for price in prices {
            if price > 10 { break #search price }
        }
        -1
    }
    println(firstOver10)   // prints 12
    return Ok(0)
}

The loop leaves the block with the first price over 10. If no price is, the loop ends and the block gives its last expression, -1.

A loop never gives a value, so break with a value inside a plain loop is an error:

Vyi · does not compile
fn main() !u8 {
    for {
        break 5   // error: `break` with a value leaves a block that produces a value
    }
    return Ok(0)
}

A block's value lives on after the block ends, so it can't point at a binding declared inside the block. The same holds for a branch of an if and an arm of a switch or match used as an expression. Declare what the value points at outside the block:

Vyi · does not compile
fn main() !u8 {
    con p = {
        mut n = 5
        &n   // error: points into storage that ends
    }
    return Ok(u8(*p))
}

defer

defer { } schedules a block to run when the enclosing function returns, by whatever path it returns. Several deferred blocks run in reverse order. This keeps cleanup next to the code that needs it:

Vyi
import { println } from "@fmt"

fn main() !u8 {
    defer { println("closing") }
    println("working")   // prints working
    return Ok(0)         // prints closing
}

Guide 08 covers defer in full, along with panic and recover.

See also the expressions reference and the statements reference.