search

What is the difference between Go's continue and break statements?

In Go, continue and break statements are used to alter the control flow of loops.

The **continue** statement is used to skip the current iteration of a loop and move on to the next iteration. It is commonly used to skip over a specific case in a switch statement. Here is an example of using **continue** in a for loop:

for i := 0; i < 10; i++ {
    if i == 5 {
        continue // skip iteration when i == 5
    }
    fmt.Println(i)
}

In this example, when **i** equals 5, the **continue** statement causes the loop to skip to the next iteration, so the number 5 is not printed.

The **break** statement is used to terminate a loop early, and move on to the next statement following the loop. Here is an example of using **break** in a for loop:

for i := 0; i < 10; i++ {
    if i == 5 {
        break // exit loop when i == 5
    }
    fmt.Println(i)
}

In this example, when **i** equals 5, the **break** statement causes the loop to terminate early, so only the numbers 0 through 4 are printed.

Related Questions You Might Be Interested