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
break labelexits that loop, not the innermost.continue labelstarts its next iteration.- It replaces the found-flag that nested loops otherwise need.
Keywords and builtins used here
continueforfuncifintrangereturn
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.
Step 3 of 4 in Control flow, step 8 of 30 in Language basics.