Introduction
Break and continue statements in Go are used to control the flow of a loop in a program. Break and continue are used together with the loop construct like a for loop. When using break and continue , they allow you to customize the logic in your program.
In this article , we will learn about the break and continue statement and how to apply them in different scenarios.
Prerequisites
- Go language run time
- Code editor, I recommend VS code, but any other editor is great
- Basic Go skills like for loops
We will cover the below topics
- Break statement
- Continue statement
- Switch , Break and continue statement
Golang Break statement
When looping through data, we often want to stop the loop if a certain condition has been met. The break statement can be used in this situation to stop the loop from continuing and return the control from the loop. Therefore , the break statement terminates the loop when it is encountered in a loop.
Syntax
for initialization; condition ; update {
break
}
Example 1 : Single Loop
package main
import "fmt"
func main() {
for i := 0; i < 10; i++ {
if i == 4 {
break
}
fmt.Println(i)
}
fmt.Println("Done")
}
Output
$ go run main.go 0 1 2 3 Done
Explanation
In the above example, we are using a for loop to loop through values from 0 to 10.
Inside the for loop , we add condition if i == 4
and terminate the loop if these conditions are met. When this condition is met, the control is return to the outer block , out of the for loop. That is why, the fmt.Println(“Done”)
get executed after the control is returned back.
Example 2 : Nested Loop
When the break statement is used in a nested loop, it will terminate the nested loop and return the control back to the outer loop.
package main
import "fmt"
func main() {
for i := 1; i < 5; i++ {
for j := 5; j > 0; j-- {
if j == i {
fmt.Printf("Outer loop %d : Inner loop :%d \n", i, j)
break
}
}
}
fmt.Println("Done")
}
Output
$ go run main.go Outer loop 1 : Inner loop :1 Outer loop 2 : Inner loop :2 Outer loop 3 : Inner loop :3 Outer loop 4 : Inner loop :4 Done
Explanation
In the above example , we have two loop counters, one count i
loop from 0 - 5
while the inner counter j
loops from 5 - 0
(reverse order). The condition we are checking is when i == j
. When this happen, we return the control back to the outer loop and continue with it. In the out put, it is clear on how the controls moves from the inner nested loop to the outer loop over and over.
Example 3 : Reading lines in a file
In this example, we are using the break statement to stop reading a file when the EOF
error has been reported. In your working directory, in the root folder, create data.log
file and add the below data.
Line one Line two Line three Line four Line Five
Then add the below code to read data from a file.
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
file, err := os.Open("data.log")
if err != nil {
log.Fatal(err)
}
defer file.Close()
buf := make([]byte, 1024)
for {
n, err := file.Read(buf)
if err == io.EOF {
fmt.Println("Done reading data.log file")
break
}
if err != nil {
log.Fatal(err)
}
if n > 0 {
fmt.Println(string(buf[:n]))
}
}
}
Output
$ go run main.go Line one Line two Line three Line four Line Five Done reading data.log file
Explanation
In the above example, we are reading data from data.log line by line. In our while loop (for {}
) we read data line by line and check if we have reached the End Of File (EOF
) error. We use the break statement to break out of the while loop when we reach the end of the file.
Golang Continue statement
The continue statement is used to skip the current iteration of a loop and pass the control to the next iteration in the loop. Unlike the break statement, continue does not break out of the loop.
Syntax
for initialization; condition; update {
if condition {
continue
}
}
Example 1 : Creating Even number array
package main
import "fmt"
func main() {
var evenNums []int
for i := 1; i < 10; i++ {
if i%2 == 0 {
evenNums = append(evenNums, i)
continue
}
}
fmt.Println("Even numbers ", evenNums)
}
Output
$ go run main.go
Even numbers [2 4 6 8]
Explanation
In the above example, we are using the continue statement to skip odd numbers in a loop.While looping, if an even number is reached , it is appended in the evenNums
array and continues to the next number skipping the current one.
Example 2: Nested loop
In a nested loop, the continue statement will skip the current iteration in the inner loop.
package main
import "fmt"
func main() {
for i := 1; i < 3; i++ {
for j := 1; j < 3; j++ {
if j == 3 {
continue
}
fmt.Printf("i -> %d j -> %d\n", i, j)
}
}
}
Output
$ go run main.go i -> 1 j -> 1 i -> 1 j -> 2 i -> 2 j -> 1 i -> 2 j -> 2
Explanation
In the above example, the inner for loop will execute the continue statement when j == 3
as indicated in the output.
Using switch, break and continue together
The select statement in Go works pretty much like the switch statement in other programming languages. The select statement can be used together with labels, break and continue statements. A label is a variable that indicates the position where the control should be returned when working with a select statement. In this section example, we are going to use a for loop together with the select statement to either break or continue code execution based on the conditions that we will add.
Example
package main
import "fmt"
func main() {
exit:
for i := 0; i < 5; i++ {
switch {
case i == 0:
fmt.Println("Starting at ", 0)
case i == 1:
fmt.Println("Progressing at ", 1)
case i == 2:
fmt.Println("Progressing at ", 2)
case i == 3:
fmt.Println("Continuing ", 3)
continue
case i == 4:
fmt.Println("Breaking ", 4)
break exit
}
}
}
Output
$ go run main.go Starting at 0 Progressing at 1 Progressing at 2 Continuing 3 Breaking 4
Explanation
In the above example, we declare a label called <b>exit </b>
in the main function. This exit label indicates the area/location/scope where the control will be returned to when we break out of the switch statement.
Next we loop through values from 0 - 5
, and use the switch statement to print data based on the current value we are looping through. For example, when current iteration == 0
, we execute fmt.Println(“Starting at “, 0)
. Our focus in this example is when the current iteration is equal to 3 or 4. When i == 3
, we call the continue statement and when i == 4
we break to the exit label, which is outside the for loop and the switch statement.
Summary
In this article, we learn about the break and continue statements. They are both used when looping through data or repeated tasks and help us to determine where to return control to. The break statement is used to terminate execution of the current loop and return control out of the current loop. On the other hand, the continue statement is used to skip the current iteration, return the control to the top of a loop and continue in a new iteration.
References
https://gobyexample.com/for
How to break out of nested loops in Go?
How to 'break' or 'continue' in GoRoutine in for loop?