Skip to content

Golang: Iterating Over Maps | Only Keys, Only Values, Both

If you need to iterate over a map in golang but you want to have only the keys or only the values then this snippet will help you a lot:

package main

import "fmt"

func main() {
	// A map: user name pointing to user id
	users := map[string]int64{
		"Morteza": 1,
		"John":    2,
		"Mike":    3,

	// Full key and value loop
	for name, id := range users {
		fmt.Println("id:", id, "name:", name)

	// Only key loop
	for name := range users {
		fmt.Println("name:", name)

	// Only value loop
	for _, id := range users {
		fmt.Println("id:", id)

Leave a Reply

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