Go continue statement

Go continue statement is used to skip the other statements in the loop for current iteration, and continue with the next iterations of the loop.

Go continue statement can be used inside a for loop statement.

In this tutorial, we will learn how to use a continue statement in for loop and nested for loop statements.

Syntax

The syntax of continue statement is

continue
ADVERTISEMENT

Examples

Continue For Loop

In the following program, we will skip further execution of statements in for block when the value of i is equal to 5, and continue with next iterations.

example.go

package main

import "fmt"

func main() {
	var i int = 0
	for i < 10 {
		if i == 5 {
			i = i + 1
			continue
		}
		fmt.Println(i)
		i = i + 1
	}
}

Output

0
1
2
3
4
6
7
8
9

We have skipped the execution of statements after continue statement in for loop for i = 5.

Break in Nested For Loop

In this example, we write a nested for loop, and use continue statement. continue statement makes execution continue with the next iteration of its immediate surrounding loop, not the outer loop.

example.go

package main

import "fmt"

func main() {
	var n int = 5
	var i int = 0
	for i < n {
		var k int = 0
		for k < n {
			if i+k >= n {
				k = k + 1
				continue
			}
			fmt.Print("* ")
			k = k + 1
		}
		fmt.Println()
		i = i + 1
	}
}

Output

* * * * * 
* * * * 
* * * 
* * 
*

Conclusion

In this Golang Tutorial, we learned about continue statement, and how to use it in a for loop, with the help of examples.