Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

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

Posted on October 20, 2023November 12, 2023 by admin

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",
}
  • Iterating over all keys and values
for k, v := range sample {
fmt.Printf("key :%s value: %s\n", k, v)
}

Output:

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

Output:

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

Output:

value :x
value :y
  • Get list of all keys
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]


  • go
  • golang
  • iteration
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP