Use of Labels - goto
Explore how to use labels and the goto keyword in Go for controlling program flow, especially within nested loops. Understand when to use continue and break with labels, avoid pitfalls like infinite loops and spaghetti code, and improve your control structures for clearer code.
We'll cover the following...
Introduction #
A label is a sequence of characters that identifies a location within a code. A code line which starts with a for, switch, or select statements can be preceded with a label of the form:
IDENTIFIER:
This is the first word ending with a colon : and preceding the code (gofmt puts it on the preceding line).
Use of labels in Go
Let’s look at an example of using a label in Go:
As you can see, we made a label LABEL1 at line 5. At line 6, we made an outer loop: for i := 0; i <= 5; i++ that will iterate 5 times. At line 7, we made an inner loop: for j := 0; j <= 5; j++ that will iterate 5 times for each i. You may have noticed that we added continue LABEL1 at line 9. The execution will jump to the label ...