In this tutorial, we will learn about the range for loop in Go. We will cover the basics of iterating over collections using the range for loop.
A range for loop in Go, also known as a for-each loop, iterates over elements in a collection such as arrays, slices, maps, or strings.
The syntax for a range for loop in Go is:
for index, value := range collection {
// Code block
}
When we use range for loop with an array as collection, we get access to the index, and element of the array in each iteration.
In the following example, we
For example,
numbers
with integer elements.package main
import "fmt"
func main() {
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf("Index: %d, Value: %d\n", index, value)
}
}
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5
When we use range for loop with a map as collection, we get access to the key, value pair of the map in each iteration.
In the following example, we
For example,
students
with key-value pairs.package main
import "fmt"
func main() {
students := map[string]int{"Alice": 20, "Bob": 25, "Charlie": 30}
for key, value := range students {
fmt.Printf("Key: %s, Value: %d\n", key, value)
}
}
Key: Alice, Value: 20 Key: Bob, Value: 25 Key: Charlie, Value: 30
When we use range for loop with a string as collection (string is a sequence of characters), we get access to the index, and character from the array in each iteration.
In the following example, we
For example,
message
.package main
import "fmt"
func main() {
message := "Hello, World!"
for index, char := range message {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Index: 0, Character: H Index: 1, Character: e Index: 2, Character: l Index: 3, Character: l Index: 4, Character: o Index: 5, Character: , Index: 6, Character: Index: 7, Character: W Index: 8, Character: o Index: 9, Character: r Index: 10, Character: l Index: 11, Character: d Index: 12, Character: !