Home ยป How to Get a Slice of Keys From a Map in Golang

How to Get a Slice of Keys From a Map in Golang

Golang map stores an unordered collection of key-value pairs. The key in the map is unique and it maps keys to values.

To get a slice of keys from a map, use the append function or MapKeys function.

In this article, we will discuss how to get a slice of keys from a map in golang.

How to Get a Slice of Keys from a Map Using the Append function

In the golang map, data is stored as a key-value pair.

To retrieve the keys from the map, refer to the below code.

package main

import "fmt"

func main() {

	// Create a map in go using the make function

	score := make(map[string]int)

	// Add elements to map
	score["Alex"] = 94
	score["Gary"] = 75
	score["Mary"] = 67

	// Create a empty slice
	keys := []string{}

	// get a slice of keys from a map using range and append function

	for key, _ := range score {
		keys = append(keys, key)
	}

	// Print the keys slice
	fmt.Println("Slice of Keys: ", keys)
}

The output of the above golang program to get a slice of keys from a map in go is:

Slice of Keys:  [Mary Alex Gary]

In the above example, to get keys from a map and append them to a slice, follow the below steps:

  1. Create a map using the make() function
  2. Add elements to the map
  3. Create an empty slice using the expression keys:= []string{}
  4. Use for range loop to iterate over each element of a map
  5. Use the Append function that takes the slice and key of a map and adds it to a slice.
  6. It adds all the keys from a map to slice
  7. Use Println to print the slice.

Cool Tip: How to check if the key exists in a map in Go!

How to Get Slice Keys from a Map Using MapKeys

The reflect.Mapkeys() function in Golang gets a slice having all the keys from a map. Import reflect package to use MapKeys() function.

Refer to the following code to get a slice containing all keys from a map.

package main

import (
	"fmt"
	"reflect"
)

func main() {

	// Create a map in go using the make function

	score := make(map[string]int)

	// Add elements to map
	score["Alex"] = 94
	score["Gary"] = 75
	score["Mary"] = 67

	// Get a slice containing all the keys from a map

	s_keys := reflect.ValueOf(score).MapKeys()
	fmt.Println(s_keys)
}

The output of the above Golang program to get keys from a map using the MapKeys() function is:

[Alex Gary Mary]

score map contains key-value pair data for students. To get a slice of keys from a map, we import package reflect and use reflect.ValueOf(score).MapKeys() expression.

Conclusion

I hope the above article on how to get a slice of keys from a map in golang is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment