How to get all the keys from map in golang?
May 02, 2022Hi 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
i++
}
fmt.Println(keys)
}
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.
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.
Happy Coding,
I hope the above example with help you to do your task.