Ad space (banner)
๐ŸนGo Lessons
Lesson 27 / 68

Representing a Set with a Map (Duplicate-Free Data)

In this lesson you will learn to represent a set with a map in Go and see a data structure put to practical use. This is for anyone searching for "Go map as a set".

Go has no dedicated Set type, but map[T]bool (a map that only records presence) gives you a duplicate-free box. Using the value as the key makes membership tests fast.

The sample code registers each value of the duplicate-containing slice {1, 2, 2, 3, 3, 3} as a map key with seen[n] = true, so the duplicates disappear automatically. Notice how len(seen) then gives the number of unique elements.

A common stumbling block for beginners is that the order of a map is not guaranteed. Unlike a slice, items are not necessarily kept in insertion order, so another structure is a better fit when order matters.

In real-world development a map-based lookup outperforms checking a slice one element at a time once there is a lot of data.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)