← Back to Go Course | Chapter 5: Arrays Slices Maps | Lesson 5 of 7

Maps

A map is like a phone book: you look up a name (the key) and it instantly tells you the matching number (the value), instead of numbering entries 0, 1, 2 like a slice.
Syntax
go
var name map[keyType]valueType
name := map[keyType]valueType{key: value}
name := make(map[keyType]valueType)

Creating a Map

A map associates keys with values, similar to a dictionary in Python or an object in JavaScript. It's created either with make(map[KeyType]ValueType) or a map literal listing initial key-value pairs.

Example: Creating a Map

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// main is where the program starts running
func main() {
	// Short declaration: create prices and infer the type
	prices := map[string]float64{
		"apple":  0.5,
		"banana": 0.25,
	}
	// Print the values followed by a newline
	fmt.Println(prices["apple"])
}

The nil Map Trap

A map declared with just 'var m map[string]int' is nil, and while reading from a nil map is safe (it returns the zero value), writing to it causes a runtime panic. This is a very common beginner mistake.

Note: Always initialize a map with make() or a literal before writing to it.

Example: The nil Map Trap

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// main is where the program starts running
func main() {
	// Declare scores with the zero value of its type
	var scores map[string]int
	// Print the values followed by a newline
	fmt.Println("read from nil map is safe:", scores["nobody"])
	scores = make(map[string]int)
	scores["alice"] = 90
	// Print the values followed by a newline
	fmt.Println(scores)
}

Checking If a Key Exists

Reading a key that doesn't exist returns the zero value for the map's value type rather than an error, which can be ambiguous. The 'comma ok' form -- value, ok := m[key] -- tells you definitively whether the key was actually present.

Note: Always use the comma-ok form when the zero value is a valid, ambiguous result (like 0 for a real score).

Example: Checking If a Key Exists

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the fmt package
import "fmt"

// main is where the program starts running
func main() {
	// Short declaration: create ages and infer the type
	ages := map[string]int{"amit": 30}
	// Short declaration: create age, ok and infer the type
	age, ok := ages["priya"]
	// Print the values followed by a newline
	fmt.Println("age:", age, "found:", ok)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing to a nil map (declared with 'var m map[K]V' but never initialized with make) which causes a runtime panic.
  2. Assuming maps preserve insertion order when iterating -- Go deliberately randomizes map iteration order.
  3. Reading a missing key and treating the returned zero value as if the key existed, instead of checking the second 'comma ok' return value.
Chapter Summary
  • A map stores key-value pairs, declared as map[KeyType]ValueType.
  • Maps must be initialized with make() or a map literal before you can write to them -- a nil map panics on write.
  • Reading a missing key returns the value type's zero value, not an error, unless you use the comma-ok form.
  • Map iteration order is randomized on purpose by the Go runtime.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.