Menu
Coddy logo textTech

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

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.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow