Go – Arrays, Slices & Maps
Estimated reading: 3 minutes 425 views

Go – Maps Explained with Syntax, Examples, and Best Practices (2025 Guide)

Introduction – What Are Maps in Go?

In Go, a map is an unordered collection of key-value pairs. Maps are ideal for fast lookups, configuration management, counters, caching, and more. They provide constant-time access to values using unique keys, making them one of the most powerful built-in data structures in Go.

In this section, you’ll learn:

  • How to declare, initialize, and access maps
  • How to add, update, and delete key-value pairs
  • Use of the comma-ok idiom for safe lookups
  • Real-world examples and best practices

Declare and Initialize a Map

Using make():

scores := make(map[string]int)

Creates an empty map where keys are string and values are int.

Using Literal Syntax:

cities := map[string]string{
    "IN": "Delhi",
    "US": "New York",
}

Output:

map[IN:Delhi US:New York]

A map can be initialized with values directly.


Add and Update Map Elements

scores := make(map[string]int)

scores["Alice"] = 90
scores["Bob"] = 75
scores["Alice"] = 95 // Update

fmt.Println(scores)

Output:

map[Alice:95 Bob:75]

Just assign to a key to insert or update values.


Access Values and Check Existence (Comma-Ok Idiom)

marks := map[string]int{"Tom": 80}

val, ok := marks["Tom"]
if ok {
    fmt.Println("Tom’s score:", val)
} else {
    fmt.Println("Not found")
}

Output:

Tom’s score: 80

ok is false if the key doesn’t exist. This is called the comma-ok idiom.


Delete a Key from Map

delete(marks, "Tom")

Removes "Tom" from the map if it exists.


Iterate Over a Map

for key, value := range cities {
    fmt.Println(key, "=>", value)
}

Order is not guaranteed—maps are unordered in Go.


Accessing Non-Existing Keys

v := cities["XYZ"]
fmt.Println(v) // Output: ""

Returns the zero value of the value type ("", 0, false, etc.).


Comparing Maps

  • You cannot compare maps directly (only to nil)
  • You must loop through keys to compare manually

Map Length and Capacity

fmt.Println(len(cities)) // Number of key-value pairs

len() gives you the number of entries in the map.


Best Practices

Do’sDon’ts
Use make() for empty maps Don’t assume map order is predictable
Use comma-ok to check existence Don’t access missing keys blindly
Use delete() to remove entries Don’t compare maps using ==

Summary – Recap & Next Steps

Go maps are fast and powerful tools for managing structured key-value data. They’re commonly used in web apps, APIs, configuration files, and anything that benefits from associative access.

Key Takeaways:

  • Declare maps with make() or literal syntax
  • Use key access and delete() to modify maps
  • Always use the comma-ok idiom for safe lookups
  • Maps are unordered and not comparable

Next: Dive into Nested Maps or explore Structs vs Maps for structured data handling.


FAQs – Go Maps

How do I check if a key exists in a map?
Use the comma-ok idiom: val, ok := map[key].

What is the default value for a missing key in a map?
The zero value of the map’s value type (e.g., 0 for int, "" for string).

Are maps ordered in Go?
No. Maps are randomly ordered for each iteration.

Can I compare two maps in Go using ==?
No. You can only compare maps to nil.

What is the zero value of a map?
A nil map, which cannot be written to until initialized.


Share Now :
Share

Go – Maps

Or Copy Link

CONTENTS
Scroll to Top