Module lessons (3/5)
for...range
for ... range is the idiomatic way to iterate over collections:
slices, arrays, maps, strings and channels. The syntax changes slightly
depending on the collection, but the base pattern is always the same:
for key, value := range coll { ... }.
Range on slices and arrays
Returns index and copy of the value:
nums := []int{10, 20, 30}
for i, v := range nums {
fmt.Println(i, v)
}
// 0 10
// 1 20
// 2 30Often one of the two is enough:
// solo indice
for i := range nums { _ = i }
// solo valore (ignora indice con _)
for _, v := range nums { _ = v }Range on a map
Returns key and value:
prices := map[string]int{"pane": 2, "latte": 3, "vino": 8}
for k, v := range prices {
fmt.Println(k, v)
}Range on a string: runes, not bytes
for i, r := range s iterates per Unicode code point (rune), not per
byte. The index i is the byte offset of the start of the rune.
for i, r := range "èé" {
fmt.Printf("%d %c (%U)\n", i, r, r)
}
// 0 è (U+00E8)
// 2 é (U+00E9)To iterate per byte use classic indexing:
s := "ciao"
for i := 0; i < len(s); i++ {
fmt.Println(s[i]) // byte (uint8)
}Range on a channel
Iterates until the channel is closed:
ch := make(chan int)
go func() {
for i := 0; i < 3; i++ { ch <- i }
close(ch)
}()
for v := range ch {
fmt.Println(v)
}We will dig deeper in the Concurrency module.
Try it
Print index and value of every element of nums using for-range.
Solution available after 3 attempts
Sum into total all values of nums ignoring the index.
Show hint
Use `_` to discard the index.
Solution available after 3 attempts
What does the first variable in `for k, v := range m` represent when m is a map?
m := map[string]int{"a": 1, "b": 2}
for k, v := range m { fmt.Println(k, v) }Recap
for k, v := range collwith clear scope: discard with_what you do not use.- Slice/array: index + COPY of the value. To mutate, index.
- Map: key + value, order randomised on every run.
- String: range iterates per rune (code point), not per byte.
- Channel: iterates while the channel is open; closed with
close().