C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Description: The first for-loop accesses only the indexes. The second accesses indexes and element values themselves.
SliceGolang program that uses range on slice
package main
import "fmt"
func main() {
colors := []string{"blue", "green", "red"}
// Use slice range with one value.
// ... This loops over the indexes of the slice.
for i := range colors {
fmt.Println(i)
}
// With two values, we get the element value at that index.
for i, element := range colors {
fmt.Println(i, element)
}
}
Output
0
1
2
0 blue
1 green
2 red
Note: In Go we refer to chars as runes. Rune has some technical meaning, but mostly is a fancy word for char.
Golang program that uses range on string
package main
import "fmt"
func main() {
// This is a string.
name := "golang"
// Use range on string.
// ... This accesses only the indexes of the string.
for i := range name {
fmt.Println(i)
}
// Use range with two variables on string.
// ... This is an index and a rune (char of the string).
for i, element := range name {
// Convert element to string to display it.
fmt.Println(i, string(element))
}
}
Output
0
1
2
3
4
5
0 g
1 o
2 l
3 a
4 n
5 g
Then: We use a range over the keys of the map. In Go, maps return their keys in a somewhat random (unpredictable) way.
Key, value: We can access both the key and the value at each pair of the map. This is an efficient way to loop over a map.
Golang program that uses range on map
package main
import "fmt"
func main() {
// An example map.
words := map[int]string{
0: "zero",
1: "one",
2: "two",
3: "three",
}
// Use range on map to loop over keys.
for key := range words {
fmt.Println(key)
}
// Range on map can access both keys and values.
for key, value := range words {
fmt.Println(key, value)
}
}
Output
2
3
0
1
3 three
0 zero
1 one
2 two