Maps

Course 1 · Ch 7
Maps: Go's Key/Value Type
The rough equivalent of a JavaScript object — but with one type for every key and one type for every value

Chapter 4 briefly used map[string]int{...} while explaining range. A Go map is the closest equivalent to a JavaScript object's key/value behaviour (Fundamentals Chapter 7) — except every key must be the same type, and every value must be the same type, declared up front as part of the map's own type.

Creating and Reading a Map

scores := map[string]int{ "maths": 88, "science": 72, "art": 95, } fmt.Println(scores["maths"]) // 88

map[string]int reads as "a map from string keys to int values." Unlike JavaScript, where an object can hold a string here and a number there, every value in this map must be an int — trying to add a string value would be a compile error.

Adding and Updating Entries

scores["history"] = 79 // adds a new key scores["maths"] = 90 // updates an existing key

Adding and updating use the same bracket-assignment syntax — Go decides which happened based on whether the key already existed, the same way JavaScript object property assignment works.

The Comma-Ok Idiom — Checking If a Key Exists

value, exists := scores["french"] if exists { fmt.Println("Score:", value) } else { fmt.Println("No score recorded for french") }

Reading a missing key from a map doesn't error — it silently returns the value type's zero value (Chapter 2), which can hide a real bug. value, exists := scores["french"] — reading TWO things from a single map lookup — is how Go distinguishes "the key exists and its value happens to be 0" from "the key genuinely doesn't exist." This pattern is called comma-ok, and appears constantly in real Go code.

A missing key looks identical to a real zero value
scores["french"] alone (without comma-ok) returns 0 whether or not "french" was ever added — there's no way to tell the difference from that single value alone. Always use the two-value form when "did this exist at all?" actually matters.

Deleting a Key

delete(scores, "art") fmt.Println(scores) // "art" is gone entirely

delete(map, key) is a built-in function (not a method) — the direct equivalent of JavaScript's delete person.isStudent from Fundamentals Chapter 7.

Looking Ahead: structs (Briefly)

type Person struct { Name string Age int } p := Person{Name: "Philip", Age: 35} fmt.Println(p.Name) // "Philip"

Maps are excellent for "any number of similarly-shaped entries" (a dictionary, a lookup table), but real-world records with a fixed set of named fields — a person, a product, an order — usually use a struct instead, Go's actual replacement for a JavaScript object literal. Structs get their own full treatment in Intermediate; this preview just establishes that p.Name uses the same dot notation as Chapter 7's JavaScript objects, even though the underlying type is completely different from a map.

JavaScriptGo
{ key: value }map[string]int{"key": value}
obj.key = valuem[key] = value
delete obj.keydelete(m, key)
obj.key === undefined to check existencevalue, exists := m[key] (comma-ok)
Mixed value types allowedAll values must be the same declared type
Fixed-shape recordstruct (preview here, full coverage in Intermediate)

Coding Challenges

Challenge 1

Create a map stock := map[string]int{"apples": 10, "bananas": 5}. Add "oranges": 8 to it, update "apples" to 15, then print the whole map.

📄 View solution
Challenge 2

Using the same stock map, use the comma-ok idiom to check for "grapes" (which doesn't exist) and "apples" (which does), printing an appropriate message for each case.

📄 View solution
Challenge 3

Create a map inventory of at least 4 items with int quantities. Use a for...range loop to print each item with its quantity, and keep a running total using a plain variable, printing the total at the end. Then delete one item and print the map again to confirm it's gone.

📄 View solution

Chapter 7 Quick Reference

  • map[KeyType]ValueType{...} — every key shares one type, every value shares another
  • m[key] = value — adds a new key or updates an existing one
  • value, exists := m[key] — comma-ok idiom; the only reliable way to check if a key exists
  • delete(m, key) — a built-in function, not a method
  • for key, value := range m { } — order is NOT guaranteed (Chapter 4)
  • type Name struct { Field type } — Go's fixed-shape record type, previewed here
  • Maps: good for dynamic/lookup-style data. Structs: good for fixed-shape records
  • This completes Go Fundamentals. Intermediate begins with structs in full, methods, and pointers.