typestar

Labeled break and continue in Go

A label names the loop, so break and continue can leave the right one.

func firstPair(values []int, target int) (int, int) {
search:
    for i, a := range values {
        for j, b := range values {
            if i == j {
                continue search
            }
            if a+b == target {
                return i, j
            }
        }
    }
    return -1, -1
}

How it works

  1. break label exits that loop, not the innermost.
  2. continue label starts its next iteration.
  3. It replaces the found-flag that nested loops otherwise need.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
198
Tokens
64
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 3 of 4 in Control flow, step 8 of 30 in Language basics.

← Previous Next →