Go break and continue

‮‬https://www.theitroad.com

In Go, the break and continue keywords are used to control the flow of execution in loops.

The break keyword is used to immediately exit a loop. It can be used in a for loop, a switch statement, or a select statement.

Here's an example of using the break keyword in a for loop:

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

In this example, the loop will iterate from 0 to 9. However, when the loop variable i becomes equal to 5, the break statement is executed, which immediately exits the loop. As a result, the loop only prints the numbers from 0 to 4 to the console.

The continue keyword is used to skip the current iteration of a loop and move on to the next iteration. It can also be used in a for loop, a switch statement, or a select statement.

Here's an example of using the continue keyword in a for loop:

for i := 0; i < 10; i++ {
    if i%2 == 0 {
        continue
    }
    fmt.Println(i)
}

In this example, the loop will iterate from 0 to 9. However, when the loop variable i is even (i.e., when i is divisible by 2), the continue statement is executed, which skips the current iteration of the loop and moves on to the next iteration. As a result, the loop only prints the odd numbers from 1 to 9 to the console.

Both the break and continue keywords are useful for controlling the flow of execution in loops and making your code more efficient and concise.