Golang – labeled break and continue

break and continue are keywords that control the loop in many programming languages. The scope of those keywords is at inner most. Here is the example code of C++.

for (int i = 0; i < 5; ++i) {
    for (int j = 0; j < 5; ++j) {
        if (i == 1 && j == 3) {
            break;
            // continue;
        }
    }
}

In the example code above, break and continue will only affect the inner most loop which deals with the variable j. However, in golang, you can control the scope of break and continue keyword by using labels.

Here is the example code.

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {
	library := `
	I am learning computer science and computer engineering
	`
	words := strings.Fields(library)
	query := os.Args[1:]

queries:
	for _, q := range query {
		for i, w := range words {
			if q == w {
				fmt.Printf("index %d: %q\n", i, w)
				break queries
			}
		}
	}
}

Let’s say there is a library of words and you are querying unique words. For example, when you query the word computer, it should return the first index of the word and the word itself. As you are running the loop, there are multiple ways to achieve this. But I want to show you that you can use a label to control the scope. You can declare the label at any scope you want and use the label with break or continue keyword. As you see in the above code, it will exit the entire thing once it finds the word.

go run main.go computer
index 3: "computer"

Leave a Reply

Your email address will not be published.