Range
The keyword range
can be used for loops. It can loopover slices, arrays, strings, maps and channels (see ). range
is aniterator that, when called, returns the next key-value pair from the “thing” itloops over. Depending on what that is, range
returns different things.
When looping over a slice or array, range
returns the index in the slice asthe key and value belonging to that index. Consider this code:
list := []string{"a", "b", "c", "d", "e", "f"}
for k, v := range list {
// do something with k and v
}
First we create a slice of strings. Then we use range
to loop over them. Witheach iteration, range
will return the index as an int
and the key asa string
. It will start with 0 and “a”, so k
will be 0 through 5, and v willbe “a” through “f”.
You can also use range
on strings directly. Then it will break out theindividual Unicode characters ^[In the UTF-8 world characters are sometimescalled runes Mostly, when people talk about characters, theymean 8 bit characters. As UTF-8 characters may be up to 32 bits the word rune isused. In this case the type of char
is rune
. and their start position, byparsing the UTF-8. The loop:
for pos, char := range "Gő!" {
fmt.Printf("character '%c' starts at byte position %d\n", char, pos)
}
prints
character 'G' starts at byte position 0
character 'ő' starts at byte position 1
character '!' starts at byte position 3
Note that ő
took 2 bytes, so ‘!’ starts at byte 3.