Go range
In Go, the range
keyword is used to iterate over the elements of an array, slice, string, or map. The range
keyword can be used in a for
loop to iterate over the elements of a collection one by one.
The syntax of the range
keyword is as follows:
for index, value := range collection { // code to be executed }
The index
variable represents the index of the current element in the collection, and the value
variable represents the value of the current element. The loop body contains the code to be executed for each element in the collection.
Here's an example of using the range
keyword to iterate over an array in Go:
arr := [5]int{1, 2, 3, 4, 5} for i, val := range arr { fmt.Println(i, val) }
In this example, the range
keyword is used to iterate over the elements of the array arr
. The loop variable i
represents the index of the current element, and val
represents the value of the current element. The loop body prints both the index and value of each element to the console.
The range
keyword can also be used to iterate over the elements of a slice:
s := []string{"apple", "banana", "cherry"} for i, val := range s { fmt.Println(i, val) }
In this example, the range
keyword is used to iterate over the elements of the slice s
. The loop variable i
represents the index of the current element, and val
represents the value of the current element. The loop body prints both the index and value of each element to the console.
The range
keyword can also be used to iterate over the characters of a string:
str := "hello" for i, ch := range str { fmt.Println(i, ch) }
In this example, the range
keyword is used to iterate over the characters of the string str
. The loop variable i
represents the index of the current character, and ch
represents the value of the current character. The loop body prints both the index and value of each character to the console.
Finally, the range
keyword can also be used to iterate over the key-value pairs of a map:
m := map[string]int{"apple": 1, "banana": 2, "cherry": 3} for key, val := range m { fmt.Println(key, val) }
In this example, the range
keyword is used to iterate over the key-value pairs of the map m
. The loop variable key
represents the current key, and val
represents the current value. The loop body prints both the key and value of each pair to the console.