Search⌘ K
AI Features

Use of Labels - goto

Explore how to implement and use labels and the goto keyword to manage control flow in Go. This lesson helps you understand their roles in loops and conditional jumps, while highlighting good practices and pitfalls to avoid for clearer and maintainable code.

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:
svg viewer

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:

Go (1.6.2)
package main
import "fmt"
func main() {
LABEL1: // adding a label for location
for i := 0; i <= 5; i++ { // outer loop
for j := 0; j <= 5; j++ { // inner loop
if j == 4 {
continue LABEL1 // jump to the label
}
fmt.Printf("i is: %d, and j is: %d\n", i, j)
}
}
}

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 ...