Consider a Go program that has a slice with indexes 0, 1, 2. With a range expression in a for
-loop we iterate over those indexes.
A range can be used on a slice, string
or map. The first variable from a range is the index. The second is the element itself (like a slice element or a rune
).
We have a slice of string
elements here—a string
slice. This slice has 3 elements. We use range in a for
-loop on the slice.
for
-loop accesses only the indexes. The second accesses indexes and element values themselves.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) } }0 1 2 0 blue 1 green 2 red
String
Here is a string
range example. We can use 1 or 2 variables in the range clause. The first is the rune
index, and the second is the rune
value itself.
char
.package main import "fmt" func main() { // This is a string. name := "abcdef" // 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)) } }0 1 2 3 4 5 0 a 1 b 2 c 3 d 4 e 5 f
Here is a map. We use int
keys and string
values. We map the English words for some numbers—this could be useful in a real program.
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) } }2 3 0 1 3 three 0 zero 1 one 2 two
int
In newer versions of Go we can use a range-int
loop, which loops from zero to the integer value specified. This repeats a loop body a certain number of times.
for
-loop can also iterate with a start, an end, and an increment statement.package main import "fmt" func main() { // Repeat a loop a certain number of times with a range int loop. for i := range 5 { fmt.Println(i) } }0 1 2 3 4
In Go we use a range expression to enumerate arrays, slices, maps, strings and channels. For most uses, a range can be used with one or two variables.