CodeBlanks Logo Icon CodeBlanks

Iterating with range

Learn to loop over slices and maps with range.

Iterating with range

range iterates over slices, arrays, maps, strings and channels. For slices it gives the index and value on each iteration:

meyveler := []string{"elma", "armut", "kiraz"}
for i, m := range meyveler {
    fmt.Println(i, m)
}
for _, m := range meyveler {   // value only
    fmt.Println(m)
}

Since Go 1.22, for i := range 5 also counts from 0 to 4.

range over maps and strings

On a map, range gives the key and value; the order is random and may change on every run. On a string it gives the byte index and the rune:

stok := map[string]int{"kalem": 3, "defter": 5}
for ad, adet := range stok {
    fmt.Println(ad, adet)
}
for i, r := range "çay" {
    fmt.Println(i, string(r))  // 0 ç, 2 a, 3 y
}

If ordered output is needed, collect the map keys into a slice and sort them first.

Practice Double the slice

Declare s := []int{1, 2, 3}. Double every element in place with a for i := range s loop and print the slice.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func main() {
    s := []int{1, 2, 3}
    for i := range s {
        s[i] *= 2
    }
    fmt.Println(s)
}

Expected output

[2 4 6]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Does <code>for _, v := range s { v *= 2 }</code> change the slice?

  • Yes, every element doubles
  • Only the first element changes
  • It doesn't compile
  • No; v is a copy of the element Correct answer

Explanation: To change the slice, write through the index: for i := range s { s[i] *= 2 }.

2 Skip the index

Question
for ____, m := range meyveler {
    fmt.Println(m)
}
Answer
for _, m := range meyveler {
    fmt.Println(m)
}

Explanation: _ ignores the unused index.

3 range target

Term Meaning
[]string index, value
map[K]V key, value
string byte index, rune
range 5 0..4

All lessons in Beginner