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

Set Operations with Maps (Union, Intersection, Difference)

In this lesson you will learn how to compute unions, intersections, and differences with maps in Go, covering the basics of set operations. This is for anyone searching for "Go map set operations".

Go has no dedicated Set type, but map[int]bool can be treated as one. Checking whether each key is present lets you compute the union, intersection, and difference.

The sample code takes the two maps {1, 2, 3, 4} and {3, 4, 5, 6}, builds the union, intersection, and difference by checking membership, and sorts each result with sort.Ints before printing so it reads clearly.

A common stumbling block for beginners is that the order of a map is not guaranteed. If you want a consistent display order, note that you have to pull the keys into a slice and sort that separately.

It is a useful way of thinking for real data work, such as finding the users common to two groups, and the ideas behind intersection and difference also carry over to understanding join operations in SQL.

๐Ÿ“– 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)