Golang : How to GOTO ?
In this tutorial, we will learn how to use goto
keyword in Golang. It has been a while since I saw this keyword goto
in a programming language and only now that I've come across goto
again in Golang. ( ...started learning how to program back when I was 12 years old with Turbo Pascal 6.0 and Quick Basic.)
There has been a raging debate about the merit of having goto
and the potential bugs that careless usage of goto
will introduce. However, this tutorial is not about pro and cons of having goto
keyword.
The codes below will demonstrate how to use a goto
to reroute the control flow back to a previously defined label within the same code block.
NOTE : The label name is case sensitive.
package main
import (
"fmt"
"os"
)
func gotoFunc() {
n := 1
GotoHere: // this is a Goto label
fmt.Println(n)
n++
if n == 9 {
fmt.Println("break goto loop")
os.Exit(0)
}
goto GotoHere // jump back to "GotoHere"
}
func main() {
gotoFunc()
}
Output :
1
2
3
4
5
6
7
8
break goto loop
You can read up more about goto
at http://en.wikipedia.org/wiki/Goto. Hope this simple tutorial can be useful to you.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.9k Golang : Check if a file exist or not
+21.6k Golang : How to reverse slice or array elements order
+7.7k Javascript : Put image into Chrome browser's console
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+16.4k Golang : Read integer from file into array
+5.8k Linux/MacOSX : Search for files by filename and extension with find command
+16.6k Golang : Set up source IP address before making HTTP request
+16.2k Golang : Send email and SMTP configuration example
+19.7k Golang : How to run your code only once with sync.Once object
+12.7k Python : Convert IPv6 address to decimal and back to IPv6
+20.6k Golang : Underscore or snake_case to camel case example
+10.8k Golang : Simple image viewer with Go-GTK