The Set Idiom in Go
Part of the Logic & Flow section of Coddy's GO journey — lesson 31 of 68.
Go doesn't have a built-in set data structure like many other programming languages. However, Go developers have created an elegant solution using maps to simulate sets, and this pattern has become so common that it's considered idiomatic Go.
The Go set idiom uses a map where you only care about the keys, not the values. Since you need to store something as the value, Go programmers use an empty struct struct{}. Here's the basic pattern:
var mySet map[string]struct{}The empty struct struct{} is special because it takes up zero bytes of memory. This makes it perfect for sets where you only need to track whether something exists or not, without wasting memory on meaningless values.
This approach leverages the fundamental property of map keys: they must be unique. When you add an item to your set, you're actually adding a key to the map. The uniqueness is automatically enforced by the map's behavior, giving you true set semantics.
In the upcoming lessons, you'll learn how to create, manipulate, and work with sets using this idiomatic Go pattern. This technique is widely used in Go codebases for tracking unique items, implementing algorithms, and solving problems where you need fast membership testing.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Cheat sheet
Go doesn't have a built-in set data structure, but uses maps to simulate sets with the idiomatic pattern:
var mySet map[string]struct{}The empty struct struct{} is used as the value type because it takes zero bytes of memory. Map keys must be unique, which automatically provides set semantics for tracking unique items.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors6Idiomatic Go: Sets
The Set Idiom in GoCreating a SetAdding to a SetChecking for MembershipRemoving from a SetIterating Over a SetRecap - Unique Usernames