Go Maps

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

var m1 = make(map[string]int) // initialized and ready to use var m2 map[string]int // nil map (not initialized)
  • Writing to m1 works normally
  • Writing to m2 will cause a runtime panic

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 of any data type.


Accessing, Adding, and Deleting Elements

Accessing Map Elements

10

Adding, Updating, and Deleting Elements

Before Delete: map[Bread:1 Milk:3] After Delete: map[Milk:3]

Checking if a Key Exists

Checking if a key exists avoids confusion when a key might legitimately be stored with a zero value.

Rahul: 80 | Exists: true Amit exists: false

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 !