Go Basics

Go Maps

Description

A map maps keys to values. It is Go's built-in hash table (dictionary). Maps must be initialized using `make` (or a literal) before use; a nil map behaves like an empty map when reading, but causes a panic when writing.

Pros & Cons

✅ Pros

  • Fast lookups O(1).
  • Built-in syntax.

❌ Cons

  • Unordered: Iteration order is not guaranteed.
  • Not thread-safe by default.

When to Use

Key-value storage and lookups.

Example

Creating, accessing, and deleting map items.

m := make(map[string]int)

m["Answer"] = 42
fmt.Println("Value:", m["Answer"])

delete(m, "Answer")

// Check existence
val, ok := m["Answer"]
if !ok {
    fmt.Println("Key missing")
}

Best Practices

Always use the `value, ok := map[key]` idiom to check if a key actually exists.

← Go StructHello World →