Docs/Language guide

Control flow

Conditions, loops, and switches with familiar, explicit structure.

Conditions#

An if statement chooses a branch using a boolean condition. Braces group statements; a single statement can follow the condition directly.

Conditions must produce a boolean. A comparison such as depth > 100 supplies one directly; a variable of type bool can also be used as the condition. Ocean evaluates the condition and executes only the selected branch. You can extend an else with another if when several conditions should be checked in order.

The example assumes depth has already been declared. Both branches are braced even though each contains one statement, which keeps the structure clear if more statements are added later.

Ocean
if (depth > 100) {
    io.Println("Deep water");
} else {
    io.Println("Near the surface");
}

A depth greater than 100 prints Deep water; every other value takes the else branch. A condition alone does not create a repeated operation. Use a loop when the test and body need to run more than once.

Counting and range loops#

Use for for both counted loops and collection traversal with range. For an array or string, two range bindings receive the index and a copy of the element; a single binding receives only the index. For a map, two bindings receive the key and a copy of the value; a single binding receives only the key. Use _ in either binding to discard it: for (_, value := range values) visits values without binding the index. for (_ := range values) runs once per entry without binding a variable.

The counted form has an initializer, a condition, and an update separated by semicolons. The initializer runs once, the condition is tested before each iteration, and the update runs as the loop advances. A for (;;) loop has no stopping condition and normally needs a break or another terminating path.

An array or string range loop evaluates its collection expression once, then visits elements in index order. A map range loop visits a snapshot of the map’s entries in unspecified order. Its element binding is a value copy. Updating that local binding does not replace the corresponding element in the original array; use indexed assignment when you need that effect.

Ocean
for (i := 0; i < 3; i++) {
    io.Println(i);
}

values := int[]{10, 20, 30};
for (index, value := range values) {
    io.Printfln("{}: {}", index, value);
}

The counted loop prints 0, 1, and 2. The range loop prints each index together with its value: 0: 10, 1: 20, and 2: 30. With only one binding, for (index := range values), that binding would receive the index.

Condition-only and deferred-condition loops#

Use for (cond) when a loop needs a condition but no initializer or update in its header. Ocean tests the condition before entering the body and again before each subsequent iteration. If it is false at the start, the body does not run. This is the form to use for a while-style loop; update the relevant state inside the body.

Adding defer before the condition skips only the first condition check. In for (defer cond), execution enters the body immediately, then tests the condition before deciding whether to repeat. The body therefore runs at least once, even if the condition would initially be false. This is useful when the body must produce or update the state that the condition examines.

The same modifier works in a three-part header: for (init; defer cond; incr). The initializer runs once, then the first body runs without a condition check. After the body, the increment runs, and only then is the condition tested. Later iterations keep that body, increment, condition order. A normal three-part loop instead checks its condition between initialization and the first body.

Condition-only and deferred-condition loops reference
Loop formExecution order
for (cond)Check → body → check → body …
for (defer cond)Body → check → body → check …
for (init; defer cond; incr)Initialize → body → increment → check → body …
Ocean
// A condition-only loop checks before its first iteration.
count := 0;
for (count < 3) {
    io.Println(count);
    count++;
}

// A deferred condition allows the first iteration unconditionally.
count = 3;
for (defer count < 3) {
    io.Println(count);
    count++;
}

// The update still runs before the deferred condition is checked.
limit := 0;
for (i := 0; defer i < limit; i++) {
    io.Println(i);
}

Place these statements inside a function in a file that imports io. The first loop prints 0, 1, and 2. The second starts with count equal to 3, so its condition would be false before entry. Because the condition is deferred, it still prints 3 once, increments count to 4, and then stops.

The final loop also runs once: it initializes i to 0, prints 0, increments i to 1, and tests 1 < 0, which is false. Without defer, the initial test 0 < 0 would prevent the body from running at all. An initializer binding such as i belongs to the loop’s scope.

continue follows the same advancement path as reaching the end of the body: it runs the update if one exists, then checks the condition. break exits directly, without running the update or another condition check. Deferring the condition does not change either rule.

Loop control#

break exits a loop and continue advances to the next iteration. Labels let nested loops break or continue a named outer loop. The range index advances independently of changes you make to its visible binding.

Use an unlabeled break or continue when you mean the innermost loop. In nested loops, a label names the loop that should receive the operation. This can be clearer than adding extra flags simply to communicate that an outer search is finished.

For a counted loop, continue advances through the update before the next condition test. For a range loop over an array or string, continue advances to the next index; for a map, it advances to the next entry. Assigning to a range binding changes that local variable, not the loop’s internal position or the original collection.

Ocean
outer: for (i := 0; i < 5; i++) {
    for (j := 0; j < 5; j++) {
        if (i + j > 4) break outer;
    }
}

In this example, break outer; leaves both loops once a pair has a sum greater than four. An unlabeled break; at the same position would leave only the inner loop, allowing the outer loop to continue.

Switches#

Value switches compare against cases in source order. A matched case does not implicitly fall into the next one; use fallthrough explicitly when needed. A default branch handles unmatched values. Condition switches and type-guard switches are also supported.

A value switch evaluates case tests in source order and runs the first matching case. Comma-separated case values share a body. The default body runs only if no case matches, regardless of where it is written. Put the default last when that makes the intended order easiest to see.

Each case normally finishes without executing the next case. fallthrough executes the next case body without requiring that next case’s test to match. Type-guard switches use the same overall structure but select by concrete type; those are described in the generics guide.

Ocean
switch (status) {
    case 0:
        io.Println("Ready");
    case 1, 2:
        io.Println("Working");
    default:
        io.Println("Unknown");
}

Assuming an integer variable named status, zero prints Ready, one or two prints Working, and another value prints Unknown. There is no need to add a break after each body to prevent an implicit fallthrough.