In this article, we will explore how to work with the continue keyword in the Go programming language.
Golang Continue Keyword
The syntax of the continue keyword is as shown:
Let us look at a few examples and understand how we can use the continue keyword.
Continue in a For Loop
The most common use case of a continue construct is inside a for loop. Take the example below:
import "fmt"
func main() {
i := 0
for i < 5 {
if i == 2 {
i++
continue
}
fmt.Println(i)
i++
}
}
In the example above, we use a for loop to iterate over the values between 1 and 5. If the value of i is equal to 2; we skip that iteration and increment the value of i by 1.
If we run the code above, we should get an output as:
3
4
Notice the code does not print 2 as that iteration is skipped.
Continue in a Nested Loop
Another classic use of a for loop is inside a nested loop. When the continue keyword is used inside a nested loop, the execution is transferred to adjacent outer loop as shown:
j := 5
for i < j {
k := 0
for k = j {
k++
continue
}
fmt.Printf("hi")
k++
}
fmt.Println()
i++
}
The above code should return:
hihihihi
hihihi
hihi
hi
Conclusion
This tutorial illustrates how to use the continue keyword to skip the current iteration or jump back to the outer loop.