HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to GoVariablesData TypesOperatorsStringsArray & SliceMap (Dictionary)Conditions (if / switch)Loops (for)Functions
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Array & Slice
🗂️ Map
🔁 Condition & Loop
🧩 Function
Go›Map (Dictionary)

Map (Dictionary)

Creating key-value mappings, accessing them, and iterating with range.

Simple enough for a 5-year-old to understand

Create and access a map

Example code
1
package main
2
import "fmt"
3
func main() {
4
person := map[string]int{"age": 36}
key is string, value is int.
Datakey is string, value is int.
5
fmt.Println(person["age"])
36
Output / Input36
6
}
DataOutput / Input
💡 Hint: Defined with map[KeyType]ValueType{}; values are accessed by key.

About this topic

A map is a Go structure that holds key-value pairs. The key type must be comparable — text, numbers, booleans, and structs are allowed; slices and maps cannot be keys because they are not comparable.

Two behaviors of maps are worth knowing. First: reading a non-existent key DOES NOT ERROR, it returns the zero value of the value type. Therefore, a two-value read form is used to check if a key actually exists.

Second: iterating over a map is RANDOM, and Go deliberately changes this on every run. The goal is to prevent you from writing order-dependent code. If you want ordered output, you must separately collect and sort the keys.

What you will learn

  • Creating a map with make
  • Writing and reading values
  • Checking for existence with a two-value read
  • Deleting a key with delete
  • Iterating with range and map order randomness
  • The nil map trap

When to use?

A map is used for looking up a record from an ID, counting, or counting duplicates. It is the natural fit for configuration, caching, and grouping tasks.

If you need to hold a set of unique values, Go doesn't have a set type; a map with empty struct values does this job with zero extra memory and is a common pattern.

Common mistakes

Wrong

var m map[string]int
m["a"] = 1

A map defined with var is nil, and WRITING to a nil map crashes with "panic: assignment to entry in nil map". Reading is fine, writing is not. You must create it with make.

Correct

m := make(map[string]int)
m["a"] = 1

Wrong

m := map[string]int{"a": 0}
if m["b"] != 0 {
	fmt.Println("b exists")
}

A non-existent key returns the zero value, so "is the value zero?" cannot be distinguished from "does the key exist?" — here key a exists but its value is zero, while b doesn't exist at all, and both look the same. The two-value read form must be used.

Correct

m := map[string]int{"a": 0}
if _, ok := m["b"]; ok {
	fmt.Println("b exists")
}

Wrong

m := map[string]int{"b": 2, "a": 1}
for k, v := range m {
	fmt.Println(k, v)
}

Map iteration order is RANDOM and changes on every run; code that relies on output order will work sometimes and fail sometimes. For ordered output, you need to collect and sort the keys.

Correct

m := map[string]int{"b": 2, "a": 1}
keys := make([]string, 0, len(m))
for k := range m {
	keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
	fmt.Println(k, m[k])
}

Frequently asked questions

How do I know if a key exists?

With the two-value read form: the second return value tells you whether the key exists. Since a single-value read returns the zero value for a non-existent key, "missing" and "zero" cannot be distinguished.

Why is map order random?

Go does this intentionally. Map order is an implementation detail, and writing code dependent on it is fragile; by randomizing it, Go makes this mistake visible during development. If you want ordered output, you must explicitly sort the keys.

Is there a set type in Go?

No, but a map with empty struct values does the trick: an empty struct takes zero bytes, so you only store the keys. This is a pattern accepted as standard in the Go community.

Summary

A map is a key-value mapping; writing to a nil map causes a panic, and a non-existent key returns the zero value. A two-value read is used for existence checks, and the iteration order is deliberately random.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code