Skip to main content
Published on

break and continue in Go

Share:

Introduction

The Go language, like many other programming languages, offers a variety of tools to control the execution flow of code. Among them, the break and continue keywords play a crucial role, especially when working with loops.

Understanding break

break is not exclusive to Go; it has its origins in earlier languages and is widely recognised by developers in many contexts. Its main role is:

  • Immediately terminate the innermost loop, whether for, switch, or select.

Let's look at a practical example to illustrate its functionality:

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

In the code above, the loop will print numbers from 0 to 4. When i reaches the value 5, the loop execution is stopped.

The depth of continue

continue, on the other hand, takes a slightly different approach:

  • It terminates the current iteration and moves directly to the next iteration of the loop.

Let's explore a scenario where this can be useful:

for i := 0; i < 10; i++ {
  if i%2 == 0 {
    continue
  }

  fmt.Println(i)
}

Here, we want to print only odd numbers. So, when we encounter an even number (i%2 == 0), we use continue to skip the print and move on to the next iteration.

Combined use of break and continue

In some situations, it may be necessary to use both together. Imagine you want to iterate over a list of numbers and stop the loop when you find a specific number, but also want to skip certain numbers.

for i := 0; i < 20; i++ {
  if i%2 == 0 {
    continue
  }

  if i == 15 {
    break
  }

  fmt.Println(i)
}

In this example, we continue to skip even numbers, but we also completely terminate the loop when i is 15.

Conclusion

Mastering the use of break and continue in Go can simplify many challenges related to flow control within loops. By deeply understanding how and when to use these keywords, you can not only make your code more readable, but also optimise the execution logic of your program.

Happy coding!