golang

Golang Continue

The continue statement is a keyword that allows you to skip a segment of a code block and jump into the next iteration. It is very common when performing operations, such as for loops and switch statements.

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:

continue

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:

package main
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:

1
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:

i := 0
j := 5
for i < j {
    k := 0
    for k = j {
            k++
            continue
        }
        fmt.Printf("hi")
        k++
    }
    fmt.Println()
    i++
}

The above code should return:

hihihihihi
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list