Sets in Go

Go does not have a built-in Set type. However, you can easily implement one using a map.

The Pattern

The most efficient way to implement a set is to use the desired type as the key and an empty struct (struct{}) as the value.

set := make(map[string]struct{})

// Add elements
set["Alice"] = struct{}{}
set["Bob"] = struct{}{}

// Check for existence
if _, ok := set["Alice"]; ok {
    fmt.Println("Alice is in the set")
}

Why struct{}?

An empty struct takes up zero bytes of memory. Using map[string]bool would also work, but each bool consumes 1 byte. In large sets, using struct{} is significantly more memory-efficient.

Distinct Counts

This pattern is ideal for counting distinct items in a collection by simply adding every item to the map and checking the map’s final length.