Welcome To Golang By Example

Different ways of iterating over a map in Go (Golang)

Range operator can be used to iterate over a map in Go

Let’s define a map first

sample := map[string]string{
        "a": "x",
        "b": "y",
}
for k, v := range sample {
   fmt.Printf("key :%s value: %s\n", k, v)
}

Output:

key :a value: x
key :b value: y
for k := range sample {
   fmt.Printf("key :%s\n", k)
}

Output:

key :a
key :b
for _, v := range sample {
   fmt.Printf("value :%s\n", v)
}

Output:

value :x
value :y
keys := getAllKeys(sample)
fmt.Println(keys)

func getAllKeys(sample map[string]string) []string {
    var keys []string
    for k := range sample {
        keys = append(keys, k)
    }
    return keys
}

Output:

[a b]