golang

Learn How to use goto statement in Golang


In this article, you will learn about how to use goto statement in Golang.

Goto statement is found in many programming languages. It is altered the normal sequence of program execution by transferring control to some other part of the program. The goto statement is also known as the unconditional jump statement.

In the Go language, you can use goto statement for the unconditional jump to a labeled statement within the same function. Let’s see the syntax for goto statement in Go language first:

goto label
..
.
label: statement

When the goto statement is triggered the control is transferred to the referred label and it is only worked inside the function where it has been declared. You will get a compilation error if you try to refer it from outside of the declared function. 

Before giving an example of the goto statement, let’s see an example of code without the goto statement:

package main

import "fmt"

func main() {
        var a int = 5

        for a < 10 {
                fmt.Printf("A = %d\\n", a)
                a++
        }
}

/* 
        Output:
                A = 5
                A = 6
                A = 7
                A = 8
                A = 9
*/ 

Here, we can see that the number is sequentially displayed from 5 to 9 based on the condition that we have implemented. Now we will skip number 7 by using the goto statement. Follow the below code:

package main

import "fmt"

func main() {
        var a int = 5
SKIP:
        for a < 10 {
                if a == 7 {
                        a = a + 1
                        goto SKIP
                }
                fmt.Printf("A : %d\\n", a)
                a++
        }
}

/*
        Output:
                A : 5
                A : 6
                A : 8
                A : 9
*/

Here, we implemented the goto statement and you can see that the moment it find the value 7 it simply skipped it by increasing the value of a and executing the rest of the code.

Important: The goto statement makes the program difficult to read and hard to trace the control flow. So, it is discouraged not to use in any programming language.


Share on social media

//