Range For Loop in Go
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.
What is a 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.
Syntax
The syntax for a range for loop in Go is:
for index, value := range collection {
// Code block
}
Example 1: Iterating over an Array
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,
- Create an array
numbers
with integer elements. - Use a range for loop to iterate over the array and print both the index and element.
Go Program
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)
}
}
Output
Index: 0, Value: 1 Index: 1, Value: 2 Index: 2, Value: 3 Index: 3, Value: 4 Index: 4, Value: 5
Example 2: Iterating over a Map
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,
- Create a map
students
with key-value pairs. - Use a range for loop to iterate over the map and print each key-value pair to the output.
Go Program
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)
}
}
Output
Key: Alice, Value: 20 Key: Bob, Value: 25 Key: Charlie, Value: 30
Example 3: Iterating over a String
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,
- Create a string
message
. - Use a range for loop to iterate over the string and print each character to output.
Go Program
package main
import "fmt"
func main() {
message := "Hello, World!"
for index, char := range message {
fmt.Printf("Index: %d, Character: %c\n", index, char)
}
}
Output
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: !