RSS Amplifier

Ashraf Latif · Aug 5, 2025

Mastering Go 9: Maps in Go – Like Dictionaries That Know Stuff 🗺️

0
Sign in to vote or save

Ashraf Latif · Ashraf Latif

Let’s say you want to store information like:

"name" → "Ashraf"
"age" → 30
"isCool" → true

You could use a list… but that’s messy.

Instead, Go gives us maps — where you use keys to get values.

A map is a collection of key-value pairs.

Think of it like:

  • A phonebook: Name → Phone number

  • A student record: ID → Marks

person := map[string]string{
  "name": "Ashraf",
  "city": "Kuala Lumpur",
}

Here:

  • map[string]string means:
    "A map where both key and value are strings"

  • "name" is the key → "Ashraf" is the value

fmt.Println(person["name"]) // Ashraf
fmt.Println(person["city"]) // Kuala Lumpur
person["age"] = "30"
person["city"] = "Penang" // updates the value

Maps are dynamic — you can add or change values anytime.

Use delete():

delete(person, "age")

This removes the "age" key (if it exists).

Sometimes, you don’t know if a key is there. Use this:

value, exists := person["name"]
if exists {
  fmt.Println("Name is", value)
} else {
  fmt.Println("No name found")
}
for key, value := range person {
  fmt.Println(key, "→", value)
}

Maps don’t have order — so don’t expect it to loop in the same sequence every time.

grades := map[string]int{
  "Alice": 90,
  "Bob":   75,
  "Cara":  88,
}
for name, score := range grades {
  fmt.Println(name, "scored", score)
}

You can have any type as the key — but most often it's string, int, or even a custom type.

map[int]string       // e.g., 1 → "First"
map[string]bool      // e.g., "seen" → true
  • Maps store key-value pairs

  • Add, update, and delete with ease

  • Use range to loop

  • Use exists check to avoid bugs

No posts

Read the original on ceghap.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.