Signup/Sign In

Continue statement in Go

Sometimes, we may want to skip the execution of a loop for a certain condition and the way to do that in Go is to make use of the continue statement. Continue statement changes the flow of the execution of the code.

The continue keyword skips the remaining part of the loop but then continues with the next iteration of the loop after checking the condition.

The following is a figure that explains the continue statement.

continue statement

Now, we know how the continue statement works in Go, it is a good time to explore the same with the help of a Go program.

Example: continue Statement in Go

Consider the example shown below:

package main

import (
	"fmt"
)
func main() {
	fruits := []string{"apple", "banana", "mango", "litchi", "kiwi"}
	for _, fruit := range fruits {
		if fruit == "litchi" {
			continue
		}
		fmt.Println("The Current fruit is:", fruit)
	}
}


The Current fruit is: apple
The Current fruit is: banana
The Current fruit is: mango
The Current fruit is: kiwi

In the above example, we are iterating over the fruits slice by making use of the range for loop and whenever we encounter a fruit whose value matches to "litchi", we are using the continue statement which will skip and code that might be written after the condition and give the control back to the starting of the loop, and the next iteration will start.

Example 2: continue Statement in Go

Let's consider one more example of the continue statement, where we will make use of the for loop that will be terminated on the basis of a condition.

Consider the example shown below

package main

import (
	"fmt"
)

func main() {
	var count int
	for count < 10 {
		count++
		if count == 5 || count == 7 {
			continue
		}
		fmt.Println("The count is:", count)
	}
	fmt.Println("Loop ended")
}

In the above example, the continue statement helps us in sipping the count when it is equal to either 5 or 7, and hence we can be sure that these two numbers will not be able to reacth the fmt.Println() statement and hence will not be present in the output.


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 6
The count is: 8
The count is: 9
The count is: 10
Loop ended

Conclusion

In the above tutorial, we learned what a continue statement is, how to use it and how it works in Go. We have explained its use with the help of examples.



About the author:
Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.