2 basic set implementations
yourbasic.org/golang
Map implementation
The idiomatic way to implement a set in Go is to use a map.
set := make(map[string]bool) // New empty set
set["Foo"] = true // Add
for k := range set { // Loop
fmt.Println(k)
}
delete(set, "Foo") // Delete
size := len(set) // Size
exists := set["Foo"] // Membership
Alternative
If the memory used by the booleans is an issue, which seems unlikely, you could replace them with empty structs. In Go, an empty struct typically doesn’t use any memory.
type void struct{}
var member void
set := make(map[string]void) // New empty set
set["Foo"] = member // Add
for k := range set { // Loop
fmt.Println(k)
}
delete(set, "Foo") // Delete
size := len(set) // Size
_, exists := set["Foo"] // Membership
Bitset implementation
For small sets of integers, you may want to consider a bitset, a small set of booleans, often called flags, represented by the bits in a single number.
See Bitmasks and flags for a complete example.
More code examples
Go blueprints: code for common tasks is a collection of handy code examples.