Go — Break statements
An unlabeled break in Go exits the innermost enclosing for, switch, or select. In this queue scan it ends the range loop immediately.
A simple example
Stop before printing 3
- Start with Visit 1 through 4
- Do this Leave at 3
- Result 1 → 2
package main
import "fmt"
func main() {
for n := 1; n <= 4; n++ {
if n == 3 {
break
}
fmt.Println(n)
}
}
1 2
Stop before the first unaffordable job
Process the queue in order with a budget of 10. Stop the loop as soon as the next job would exceed the remaining budget. Range supplies each cost in arrival order. A failed budget check leaves the remaining balance and accepted count untouched.
A print queue has ten credits and must serve jobs in arrival order. Jobs costing four and three leave three credits. The next job costs eight, so the queue stops before the smaller job behind it.
Run the example
Use Go 1.21 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func main() {
remaining, accepted := 10, 0
for _, cost := range []int{4, 3, 8, 1} {
if cost > remaining {
break
}
remaining -= cost
accepted++
}
fmt.Printf("%d accepted, %d left\n", accepted, remaining)
}
2 accepted, 3 left
The first two jobs cost 4 and 3, leaving 3. The next costs 8, so processing stops before the later job costing 1.
Try it yourself
Replace the cost of 8 with 3. What changes?
Check your answer
The third job exactly fits. Three jobs are accepted and the remaining budget is zero. The last job cannot run.