Skip to Content
Course content

90: Working with Sets Using Maps

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

Imagine you're managing a guest list for a high-profile event. When someone arrives at the door, you don't need to know their favorite color or their phone number; you just need to know one thing: Is their name on this list? If "Alice" is on the list three times by mistake, she still only gets one entry into the party. You aren't mapping a name to a value; you're simply tracking the existence of a key.

In Go, we don't have a dedicated Set type like you might find in Python or Java. Instead, we use maps to do the heavy lifting. Here is how that guest list analogy maps directly to our code:

  • The Guest List is the map.
  • The Guest's Name is the key.
  • The "Checkmark" (the fact that they are on the list) is the value.

The Magic of the Empty Struct

Now, you might be tempted to use a map[string]bool. If the value is true, they're in the set. That works, but it's not how experienced Go engineers do it. A boolean takes up 1 byte of memory. While that seems tiny, if you're tracking a million unique IDs, those bytes add up.

Instead, we use an empty struct: struct{}. In Go, an empty struct occupies zero bytes of storage. It is the ultimate signal to the compiler and other developers that you don't actually care about the value—you only care that the key exists.

package main

import "fmt"

func main() {
    // We define a set of unique IP addresses
    // Key: string (the IP), Value: empty struct (zero memory)
    visitedIPs := make(map[string]struct{})

    // Adding elements to the set
    visitedIPs["192.168.1.1"] = struct{}{}
    visitedIPs["10.0.0.5"] = struct{}{}
    visitedIPs["192.168.1.1"] = struct{}{} // Duplicate! Doesn't matter.

    fmt.Println("Total unique IPs:", len(visitedIPs))
}

Checking for Presence and Removing Items

Since the value is useless to us, we use the "comma ok" idiom to check if a key exists. I've seen a lot of beginners try to retrieve the value, but we just use the blank identifier _ to discard it.

To remove someone from the set, the built-in delete function works exactly as it does for any other map. It doesn't matter that the value is an empty struct; the key is what's being scrubbed.

// Check if an IP has visited before
ip := "10.0.0.5"
if _, ok := visitedIPs[ip]; ok {
    fmt.Printf("IP %s is already in the set\n", ip)
}

// Remove an IP from the set
delete(visitedIPs, "10.0.0.5")

When to Actually Use This

I generally reach for this pattern in three specific scenarios: removing duplicates from a slice, performing set intersections (finding what two lists have in common), or maintaining a "seen" list during a recursive crawl (like walking a file system so you don't get stuck in a symbolic link loop). It's a simple pattern, but mastering it makes your Go code feel idiomatic.




📋 Practical Task

Build a Unique Blog Tag Extractor

You are building a feature for a blog CMS. You have a list of posts, and each post has a slice of tags. Because different authors use different tags for the same topics (e.g., "golang", "go", "go-lang"), you need to create a utility that extracts every unique tag used across all posts into a single list.

Your Task:

  1. Create a slice of structs called Post, where each struct has a Title (string) and Tags ([]string).
  2. Initialize a slice of 3-5 Post objects with overlapping tags.
  3. Write a function ExtractUniqueTags(posts []Post) []string that:
    • Uses a map[string]struct{} to track every tag encountered.
    • Iterates through all posts and all tags within those posts.
    • Converts the final map keys back into a slice of strings.
  4. Print the final slice of unique tags to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.