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
+18.5k Golang : How to make function callback or pass value from function as parameter?
+5.1k Golang : Reclaim memory occupied by make() example
+13.9k Golang : How to pass map to html template and access the map's elements
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+8.7k Golang : Serving HTTP and Websocket from different ports in a program example
+27.9k Golang : Change a file last modified date and time
+8.9k Golang : Write multiple lines or divide string into multiple lines
+11.4k Golang : GTK Input dialog box examples
+5.8k Golang : Convert Chinese UTF8 characters to Pin Yin
+34.6k Golang : Upload and download file to/from AWS S3
+10.1k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+6.8k Golang : Fixing Gorilla mux http.FileServer() 404 problem