Limited Offer
60% OFF on all plans!

Set in Go

Implement set behavior in Go using maps: uniqueness, add/remove, membership, traversal, conversion, and set operations.

Set Basics

Go has no built-in set type, but you can use a `map[T]struct{}` (or `map[T]bool`) to represent a set of `T`. Keys are the elements; presence in the map means membership.

1. Creating an Empty Set

Use make(map[T]struct{}).

2. Creating a Set from a Slice

Insert elements from a slice; duplicates collapse.

Basic Set Operations

Use map assignment (`set[x] = struct{}{}`) to add, `delete` to remove, the two-value form to test membership, `len` for size, and `make` to clear.

1. Adding Values to a Set

Assignment inserts an element.

2. Checking if a Value Exists

Use the two-value form to test membership.

3. Removing a Value

Use delete(set, value).

4. Clearing the Set

Reinitialize the map.

5. Getting Set Size

Use len(set).

Traversing a Set

Because a set is backed by a map, you iterate over keys with `for range`. Order is not guaranteed.

1. Traversing using for range

Iterate over keys (elements).

Converting Between Set and Slice

Helpers that convert between `[]T` and a set type (like `IntSet`) make it easy to deduplicate and to interoperate with slice APIs.

1. Converting Set to Slice

Collect keys into a slice.

2. Removing Duplicates from a Slice

Use a set to filter unique values.

Set Operations (Union, Intersection, Difference)

With map-backed sets, union, intersection, and difference are simple to express as loops over keys.

1. Union, Intersection, Difference

Return new sets for each operation.