Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

Listen, I've seen this exact bug trip up dozens of junior devs: the assumption that if you get a value back from a map, that key actually existed in the map. In many languages, accessing a missing key throws an error or returns null. In Go, it doesn't. It returns the zero value for the map's value type.

The Zero Value Trap

Imagine you're building a simple game where you track player scores in a map. You might write something like this:

scores := map[string]int{"Alice": 10, "Bob": 0}

fmt.Println(scores["Charlie"]) // Output: 0

At first glance, you might look at that 0 and think, "Oh, Charlie is in the game and he hasn't scored any points yet." But Charlie isn't even in the map. Go just saw that you wanted an int and, since the key was missing, it gave you the default int value of 0. This is dangerous because you can't tell the difference between a player who is missing and a player who actually has a score of zero.

The "Comma Ok" Idiom

To fix this, you need to use what we call the "comma ok" idiom. When you access a map, Go can actually return two values: the value itself, and a boolean that tells you if the key was actually present.

scores := map[string]int{"Alice": 10, "Bob": 0}

if val, ok := scores["Charlie"]; ok {
    fmt.Printf("Charlie's score is %d\n", val)
} else {
    fmt.Println("Charlie isn't in the system!")
}

if val, ok := scores["Bob"]; ok {
    fmt.Printf("Bob's score is %d\n", val) // This will actually print!
}

I always recommend using this pattern whenever a zero value is a legitimate piece of data in your domain. It's the only way to be certain about the state of your data.

Initializing and Managing Your Data

You have two main ways to get a map started. For small, known sets of data, use a map literal. For dynamic data—like things you're loading from a database—use make.

// Literal: Great for configuration or fixed lookups
routes := map[string]string{
    "/":     "Home Page",
    "/about": "About Us",
}

// make: Essential for empty maps you intend to fill later
userCache := make(map[int]string)
userCache[101] = "Jane Doe"

One quick warning: never try to add an element to a nil map (a map declared without make or a literal). Your program will panic and crash instantly. Always initialize your maps.

When it comes to removing items, Go provides the built-in delete function. It's clean, and interestingly, it doesn't care if the key exists or not—if the key is already gone, delete just does nothing without complaining.

delete(routes, "/about")

Maps are Reference Types

Here is a nuance that often surprises people: maps are reference types. If you pass a map into a function and that function modifies the map, the original map is changed. You aren't passing a copy of the map; you're passing a pointer to the underlying data structure.

I've found this incredibly useful for sharing state across different parts of a program, but it can lead to "spooky action at a distance" if you aren't careful. If you need to protect a map from being changed, you'll either need to copy it manually into a new map or use a sync.Mutex if you're working with goroutines (which we'll tackle in a later lesson).




📋 Practical Task

Build a DNS Cache Simulator

Your task is to create a small program that simulates a DNS cache. You need to implement a system that stores domain names (keys) and their corresponding IP addresses (values).

Requirements:

  • Create a map called dnsCache.
  • Add three entries to the map: "google.com", "github.com", and "golang.org".
  • Write a function called resolve(domain string) that:
    • Checks if the domain exists in the cache using the "comma ok" idiom.
    • If it exists, prints: "IP found: [IP address]".
    • If it doesn't exist, prints: "Domain not found in cache".
  • In your main function, call resolve for a domain that exists and one that doesn't.
  • Use the delete function to remove "github.com" from the cache, then call resolve("github.com") again to verify it's gone.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.