Skip to main content

Go Ep 5: Maps & Hash Tables

Rachmat Hidayat
Author
Rachmat Hidayat
Learn & sharing insights on TypeScript, Go, Kubernetes, DevOps, DevSecOps, SRE, Platform Engineering, AI/ML Engineering, and MLOps.
go - This article is part of a series.
Part 5: This Article
Maps provide fast $O(1)$ key-value lookups. Understanding map initialization and comma-ok lookups is essential for safe data manipulation.

TL;DR (Quick Summary)
#

  • Map (map[KeyType]ValueType): An unordered hash table. KeyType must be comparable (strings, numbers, pointers). Uninitialized maps are nil.
  • Comma-OK Map Lookup: val, exists := myMap["key"]. Checks if a key actually exists without getting a false positive on zero values.
  • Delete Key: delete(myMap, "key") removes a key-value pair cleanly.

1. Map Operations & Comma-OK Idiom
#

package main

import "fmt"

func main() {
	// 1. Initializing a map using make()
	userRoles := make(map[string]string)

	// 2. Insert & Update
	userRoles["rachmat"] = "admin"
	userRoles["alice"] = "developer"

	// 3. Delete a key
	delete(userRoles, "alice")

	// 4. Comma-OK Lookup (Checking key existence)
	role, exists := userRoles["bob"]
	if !exists {
		fmt.Println("User 'bob' not found in map!")
	} else {
		fmt.Println("Bob's Role:", role)
	}

	// 5. Iterating over a map
	for user, r := range userRoles {
		fmt.Printf("User: %s -> Role: %s
", user, r)
	}
}

2. Troubleshooting & Common Errors
#

Error 1: panic: assignment to entry in nil map
#

The Cause: Writing a key to a map variable declared without initialization (var m map[string]int).

// 🔴 Dangerous: Panics!
var m map[string]int
m["key"] = 42

// 🟢 Fix: Initialize using make() or literal syntax
m := make(map[string]int)
m["key"] = 42

Summary & Next Steps
#

In this episode:

  • We performed CRUD operations on Go Maps and used comma-ok lookups.
  • We iteration and key deletion on maps.

In Episode 6: Structs, Fields & JSON Serialization, we will master custom composite Structs!

go - This article is part of a series.
Part 5: This Article