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 numberA student record:
ID → Marks
person := map[string]string{
"name": "Ashraf",
"city": "Kuala Lumpur",
}Here:
map[string]stringmeans:
"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 Lumpurperson["age"] = "30"
person["city"] = "Penang" // updates the valueMaps 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" → trueMaps store key-value pairs
Add, update, and delete with ease
Use
rangeto loopUse
existscheck to avoid bugs
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.