Go
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions and Methods
-
Section 4: Concurrency
-
Section 5: Packages and Tooling
-
Section 6: More Standard Library
-
Section 7: Building Services
-
Section 8: Advanced Go
-
Section 9: Go in the Cloud-Native Ecosystem
-
Section 10: Data Structures and Algorithms in Go
-
Section 11: Testing and Deployment
-
Section 12: Practical Projects
-
Section 13: More Standard Library Practice
-
Section 14: More Practice Projects
-
Section 15: Design Patterns in Go
-
Section 16: Interview Practice
-
Section 17: Package fmt In Depth
-
Section 18: Package strings and strconv
-
Section 19: Package os and io
-
Section 20: Package time
-
Section 21: Package sort and container
-
Section 22: Package encoding
-
Section 23: Package net/http In Depth
-
Section 24: Package context
-
Section 25: Package regexp and bytes
-
Section 26: Package errors In Depth
-
Section 27: Package crypto and hash
-
Section 28: Package flag and log
-
Section 29: Package sync In Depth
-
Section 30: More Practice Exercises
-
Section 31: Go Modules and Workspaces In Depth
-
Section 32: Generics Deep Dive (Go 1.18+)
-
Section 33: Testing Package In Depth
-
Section 34: More Interview and Whiteboard Practice
-
Section 35: Package math and unicode
-
Section 36: Package path and filepath
-
Section 37: Package database/sql
-
Section 38: Package text/template and html/template
-
Section 39: Package archive and compress
-
Section 40: Lower-Level net Package
-
Section 41: Package runtime and reflect
-
Section 42: Package embed and io/fs
-
Section 43: Go Assembly and CGO Basics
-
Section 44: Building CLIs and TUIs
-
Section 45: Go Performance Tuning
-
Section 46: More Real-World Projects
-
Section 47: Go in Production
-
Section 48: Go Design Patterns
-
Section 49: Go Interfaces Deep Dive
-
Section 50: Final Practice and Review
90: Working with Sets Using Maps
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:
- Create a slice of structs called
Post, where each struct has aTitle(string) andTags([]string). - Initialize a slice of 3-5
Postobjects with overlapping tags. - Write a function
ExtractUniqueTags(posts []Post) []stringthat:- 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.
- Uses a
- Print the final slice of unique tags to the console.
There are no comments for now.