How to get all the keys from map in golang?

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To get all keys from map, you can use range to get key from map and store in an new array where you can store all keys and use wherever you want.

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

When run above program you will get a golang map keys basically range is loop which can help you get key from map in golang.

Using fmt.Println method golang print all keys in map.

Let’s see actual output of the code.

get, all the keys from map, golang

Here, we are provided code onecompiler links for the above program for get all keys from map. Then you can use it whenever you want and do the changes as per your requirements.

Try it yourself

Happy Coding,

I hope the above example with help you to do your task.

Premium Content

You can get all the below premium content directly in your mail when you subscribe us


Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts