'Goto' statement is used to skip a few lines of code below it.
We can make the best use of as a loop.
Let us make it simple with the below example.
Say we have a 'for loop' that prints the numbers from 1, 2 and 3.
package main import "fmt" func main() { for i := 1; i <= 3; i++ { fmt.Println(i) } }
Now, let's say, want to get the same output
And this time we won't be using any kind of loops. Just use 'goto' and make it work as a loop.
Let us rewrite the program using 'goto' statement.
package main import "fmt" func main() { i := 1 MyLoop : fmt.Println(i) if (i < 3) { i++ goto MyLoop } }
Now, if you see the output, the numbers 1, 2 and 3 are printed.
Let us see it in detail :
Initially we have created a variable called 'i' and assigned it with '1'.
So, we have something called as level, i.e. 'MyLoop' followed by colon ':'.
And the so called 'loop' with 'goto' happens in the next few lines.
MyLoop : fmt.Println(i) if (i < 3) { i++ goto MyLoop }
And the Iteration starts,
In the 1st Iteration, '1' is already stored in the variable 'i'.
In the next line, we have the print statement.
Printing the value of 'i'.
So, in the next line, we check if the value of the variable 'i' is less than '3' or not.
if (i < 3) { i++ goto MyLoop }
What happens is the value of 'i' gets incremented by 1 and becomes 2.
Then we come to the 'goto' statement. Which asks the loop to goto the Level 'MyLoop'.
Then we start the second Iteration.
In the 2nd Iteration, the value of 'i' is '2'.
In the next line, we have the print statement.
Printing the value of 'i'.
And the 3rd Iteration starts.
And in the same way the values are printed using 'goto'.