How to get all the keys from map in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

Today, we are going to do how to get all the keys from the map in golang, here we will write simple logic to extract all keys from the map using loops.

Well, First we will create a map variable with sample data, after that we will create the keys variable where we will store our keys.

After the creation of the variable, we will write a range where we can get a key to map, and we will store those keys in our keys variable one by one.

Let’s start our code part.

package main
import "fmt"

func main() {
  mymap := map[int]string{
        1: "Hello",
        2: "World",
        3: "Of Infinitbility",
    }

	keys := make([]int, len(mymap))

  i := 0
  for k := range mymap {
    keys[i] = k
    i++
  }
  fmt.Println(keys)
}

When run above program you will get a array of keys. let’s see our output.

Let’s see actual output of the code.

get, all the keys from map, golang

Try it yourself

All the best 👍

Follow me on Twitter