Go proposal accepted: a generic Set type
A proposal for a generic[1] Set type has been accepted in the golang/go repository, tracked as issue #69230. The proposed type, Set[Elem comparable][2], has a zero value that is an empty set ready to use. Its methods are Add, Remove, Contains and Len, plus an All() iterator over the elements, alongside the package-level functions Union, Intersection and Difference. The proposal builds on the discussion in #47331 and on Go's range-over-func iterators[3]; two weeks earlier there had been an attempt to reopen the topic (#69033).
The latest update moves the package to golang.org/x/exp/collection/set, renames SetOf back to Of and CollectSet back to Collect. A Set[E] is transparently represented as a map[E]struct{}[4], so it can be used directly as the operand of a range loop. The package is described as an experimental prototype for what may become the canonical representation of a set recommended for use in public APIs.
A comment in the thread traces earlier set proposals: #7088 from January 2014, closed because generics would let developers define their own Set type; #22812 from November 2017 and #61884 from August 2023, both closed as duplicates; and #47331 from July 2021, closed because it depended on the outcome of the iteration proposal #61405. A related August 2021 proposal, #47963, asked more generally what to do with the existing container packages after generics arrived and is not directly about sets.
Read the original github.comDiscussion
Discussion
Commenters largely propose API refinements: renaming the All() iterator to Values() because it yields only elements, and adding a set.From constructor that accepts an iterator to build a set from a map or slice. One commenter shared a draft API of their own, still weighing whether set-returning functions should return Set[E] or *Set[E].
Sources
-
GitHub
Proposal Accepted: Generic Sets


