休息和繼續

與許多其他語言一樣,Go 也支援打破迴圈並繼續下一次迭代:

for x := 0; x < 10; x++ { // loop through 0 to 9
    if x < 3 { // skips all the numbers before 3
        continue
    } 
    if x > 5 { // breaks out of the loop once x == 6
        break
    }
    fmt.Println("iteration", x)
}

// would print:
// iteration 3
// iteration 4
// iteration 5

breakcontinue 語句還接受一個可選標籤,用於標識外部迴圈以使用以下語句進行定位:

OuterLoop:
for {
    for {
        if allDone() {
            break OuterLoop
        }
        if innerDone() {
            continue OuterLoop
        }
        // do something
    }
}