Go Range Keyword

In Go, the range keyword is used to iterate over elements of an array, slice, string, map, or channel. It provides a convenient way to loop over the elements without explicitly managing indices or iterators. The range keyword returns both the index and value of each element during the iteration. Here’s how you can use the range keyword:

  1. Iterating over an array or slice:
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
    fmt.Println(index, value)
}

In this example, the range keyword is used to iterate over each element of the numbers slice. The index variable stores the index of the current element, and the value variable stores the corresponding value. The output will be:

0 1
1 2
2 3
3 4
4 5
  1. Iterating over a string:
message := "Hello, World!"
for index, char := range message {
    fmt.Println(index, string(char))
}

Here, the range keyword is used to iterate over each character of the message string. The index variable stores the index of the current character, and the char variable stores the character itself. The string() function is used to convert the character to a string for printing. The output will be:

0 H
1 e
2 l
3 l
4 o
5 ,
6
7 W
8 o
9 r
10 l
11 d
12 !
  1. Iterating over a map:
studentScores := map[string]int{
    "Alice":  85,
    "Bob":    92,
    "Charlie":78,
}
for name, score := range studentScores {
    fmt.Println(name, score)
}

In this example, the range keyword is used to iterate over the studentScores map. The name variable stores the key (student name), and the score variable stores the corresponding value (score). The output will be:

Alice 85
Bob 92
Charlie 78

The range keyword simplifies the process of iterating over various data structures in Go. It provides a concise way to access both the index and value of each element within a loop.