Skip to content

Go: Get the List of Map Keys

In Golang, you don’t have a special function that extracts the map keys for you. But it is as simple as this loop:

package main

import "fmt"

func main() {
	translations := map[string]string{
		"hi_msg":      "Hi!",
		"my_name_msg": "My name is",
		"welcome_msg": "Welcome to my website :)",
	}

	// Use make() to create the slice for better performance
	translationKeys := make([]string, 0, len(translations))

	// We only need the keys
	for key := range translations {
		translationKeys = append(translationKeys, key)
	}

	fmt.Println(translationKeys)
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *