Maps, Structs, and Pointer Receivers
Look up map keys safely with value, ok, avoid nil map panics, define structs, and choose value vs pointer receivers. After this, you can model structured data and mutate state predictably.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Slices hold ordered lists, but most real programs need fast key-value lookups (maps) and named domain records that enforce rules (structs with methods). Go has no class keyword: a struct holds the fields, methods attach behavior to that struct, and the difference between a value receiver and a pointer receiver decides whether your method actually modifies the struct or silently edits a throwaway copy.
Skip ahead
If you already initialize maps with make, check missing keys with comma-ok, and know when to choose pointer receivers (*T) over value receivers (T), take the section quiz or continue to "Handle Errors Without Hiding Them."
Experiment 1: Why reading a missing map key returns zero—and how comma-ok fixes it
Imagine an inventory map tracking product stock counts. A product can legitimately have 0 units left in stock—or it might not exist in your catalog at all. Looking up a missing key in a Go map never crashes; it simply returns the value type's zero value (0). Use the two-value comma-ok lookup to tell the two cases apart:
stock := map[string]int{"KB-01": 0, "MS-02": 5}
for _, sku := range []string{"KB-01", "UNKNOWN"} {
qty, ok := stock[sku]
fmt.Printf("sku=%s qty=%d exists=%v\n", sku, qty, ok)
}
sku=KB-01 qty=0 exists=true
sku=UNKNOWN qty=0 exists=false
Notice both keys returned qty=0, yet only ok revealed that KB-01 is an out-of-stock product while UNKNOWN is an invalid SKU.
Experiment 2: The nil map panic
While reading from a nil map is safe (returns zero, false), writing to a nil map panics immediately:
var m map[string]int // zero value is nil
// m["KB-01"] = 5 // PANIC: assignment to entry in nil map!
m = make(map[string]int) // initialized and ready for writes
m["KB-01"] = 5
Always initialize maps with make(map[K]V) or a literal map[K]V{} before inserting keys—especially map fields inside a struct.
Experiment 3: Value receivers vs. pointer receivers
Go attaches methods to a struct by placing a receiver between func and the method name. Watch what happens when you write a method that increments a counter with a value receiver (Counter) versus a pointer receiver (*Counter):
type Counter struct {
Name string
Count int
}
func (c Counter) IncWrong() { c.Count++ }
func (c *Counter) IncRight() { c.Count++ }
func main() {
c := Counter{Name: "hits"}
c.IncWrong()
fmt.Println("after IncWrong:", c.Count)
c.IncRight()
fmt.Println("after IncRight:", c.Count)
}
after IncWrong: 0
after IncRight: 1
Because Go passes receivers by value just like normal parameters, IncWrong received a copy of c, bumped Count on that copy to 1, and threw the copy away when the method returned. IncRight received *Counter—a pointer to the caller's struct—so c.Count actually updated to 1.
Experiment 4: Putting data and rules together in a real Order struct
Just like classes in Python or Java, structs with pointer-receiver methods keep data and business rules in one place—so no caller can add items to an order after it has been paid:
type Order struct {
Customer string
Items []string
Status string
}
func (o *Order) AddItem(item string) error {
if o.Status != "open" {
return fmt.Errorf("cannot add %q to %s order", item, o.Status)
}
o.Items = append(o.Items, item)
return nil
}
func (o *Order) MarkPaid() { o.Status = "paid" }
func main() {
ord := Order{Customer: "Ana", Status: "open"}
_ = ord.AddItem("Keyboard")
ord.MarkPaid()
err := ord.AddItem("Cable")
fmt.Printf("items=%v status=%s err=%v\n", ord.Items, ord.Status, err)
}
items=[Keyboard] status=paid err=cannot add "Cable" to paid order
Notice one ergonomic Go touch: ord is a plain value (Order), yet calling ord.AddItem("Keyboard") works automatically—because ord is addressable, Go rewrites it to (&ord).AddItem(...) behind the scenes.
Common mistakes
- Writing to an uninitialized map field on a struct: Creating
Cache{}leaves itsdata map[string]stringfield asnil; provide aNewCache()constructor that callsmake(...). - Mixing value and pointer receivers on the same struct: If even one method needs a pointer receiver (
*Order) to mutate state, give all methods onOrdera pointer receiver so the method set stays consistent. - Sharing a map across goroutines without a lock: Concurrent map read+write crashes the entire Go runtime with a fatal error that
recover()cannot catch.
💡 Tip
Deleting a key that does not exist (delete(stock, "UNKNOWN")) is a safe no-op in Go—you never need an if _, ok := stock[k]; ok check before calling delete.
What happens if you skip this step
Forgetting make on a map causes runtime crashes on the first write; choosing a value receiver on a mutating method compiles cleanly while silently discarding every state change.
Why does qty := stock["UNKNOWN"] compile and run without error, and how could that hide a bug in a checkout service?
About
Look up map keys safely with value, ok, avoid nil map panics, define structs, and choose value vs pointer receivers. After this, you can model structured data and mutate state predictably.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.