2 basic set implementations

yourbasic.org/golang

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 require 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

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: