Search⌘ K
AI Features

Break and Continue

Explore how to use break and continue statements in Go to control the flow within loops. This lesson teaches you how to terminate loops early or skip iterations under certain conditions, improving your ability to write efficient and clear loop control structures in Go.

Introduction

Sometimes, we may want to skip the execution of a loop for a certain condition or terminate it immediately without checking the condition. To specifically change the flow of execution, we have another two statements, break and continue.

break statement

In every iteration, a condition has to be checked to see whether the loop should stop. If the exit-condition becomes true, the loop is left through the break statement. A break statement always breaks out of the innermost structure in which it occurs; it can be used in any for-loop (counter, condition, and so on), but also in a switch, or a select statement. Execution is continued after the ending } of that structure. The following figure explains the break statement.

Run the following program to understand ...