Go Maps
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Go Maps

Kishore V

Go Maps

In Go, a map is a built-in data type used to store data in key–value pairs. Each key is unique and maps to a specific value, making maps ideal for fast lookups and dynamic data storage.

Unlike arrays or slices, maps are:

  • Unordered (no guaranteed iteration order)
  • Mutable (you can add, update, and delete elements)
  • Reference types (they point to an underlying hash table)

Key Features of Maps

  • Store data as key:value pairs
  • Keys must be unique (no duplicates allowed)
  • The len() function returns the number of elements
  • The zero value of a map is nil
  • Internally implemented using a hash table for efficient access

Creating Maps in Go

1. Using Map Literals

Countries: map[IN:India JP:Japan US:United States] Scores: map[Alice:90 Bob:85 Eve:88]

Note: Map output order may vary because maps are unordered.

2. Using the make() Function

Inventory: map[Apples:50 Bananas:30 Oranges:20]

Creating an Empty Map Safely


Allowed Key and Value Types

Valid Key Types

Keys must support the == operator:

  • Numbers (int, float, etc.)
  • Strings
  • Booleans
  • Arrays
  • Structs
  • Pointers
  • Interfaces (if comparable)

Invalid Key Types

These cannot be used as keys:

  • Slices
  • Maps
  • Functions

Value Types

Map values can be any data type.

Accessing Map Elements


Adding and Updating Elements


Deleting Elements


Checking if a Key Exists


This pattern avoids confusion when a key might exist with a zero value.

Maps Are Reference Types

Maps do not store data directly—they reference an underlying structure. Assigning one map to another shares the same data.

Original: map[A:100 B:2] Copy: map[A:100 B:2]

Both variables reflect the same change.

Iterating Over a Map

Pen : 10 Pencil : 5 Eraser : 3

The iteration order is not guaranteed.

Iterating in a Specific Order

To control the order, use a separate slice of keys:

one : 1 two : 2 three : 3


Our website uses cookies to enhance your experience. Learn More
Accept !