Working with Range in Go

11.12.2021

Intro

The range keyword can be used with the for keyword to loop through Go data types. We can loop through arrays, slices, maps, and channels. In this article, we will learn how to use Go range.

Using Range

There are two basic ways to use the for and range keyword. You can either return just the index, or key for maps, or you can return the index and values. Let's look at some examples.

For arrays and slices, we can iterate over the object while returning only the index or the index with the value.

// Create a slice
numbers := []int{1, 2, 3}

// Loop with only the index
for index := range numbers {
	fmt.Println("Index: ", index, "Number: ", numbers[index])
}

// Loop with index and value
for index, number := range numbers {
	fmt.Println("Index: ", index, "Number: ", number)
}

Similar for Maps, we can do the same, except we return the keys.

// Create a Map
phoneMap := make(map[string]string)
phoneMap["Jen"] = "555-5555"
phoneMap["Jane"] = "666-6666"

// Loop with only the key
for person := range phoneMap {
	fmt.Println("Person: ", person, " Phone: ", phoneMap[person])
}

// Loop with the key and value
for person, phone := range phoneMap {
	fmt.Println("Person: ", person, " Phone: ", phone)
}

Full Example

Below is the full example code. You can run this by copying the contents to a file called main.go and run go run main.go.

package main

import "fmt"

func main() {
	// Create a slice
	numbers := []int{1, 2, 3}

	// Loop with only the index
	for index := range numbers {
		fmt.Println("Index: ", index, "Number: ", numbers[index])
	}

	// Loop with index and value
	for index, number := range numbers {
		fmt.Println("Index: ", index, "Number: ", number)
	}

	// Create a Map
	phoneMap := make(map[string]string)
	phoneMap["Jen"] = "555-5555"
	phoneMap["Jane"] = "666-6666"

	// Loop with only the key
	for person := range phoneMap {
		fmt.Println("Person: ", person, " Phone: ", phoneMap[person])
	}

	// Loop with the key and value
	for person, phone := range phoneMap {
		fmt.Println("Person: ", person, " Phone: ", phone)
	}
}