Go: How to implement a set

The idiomatic way to implement a set in Go is to use a map, where the keys in the map represent the elements in the set.

For simplicity true is typically used as dummy value.

Set operations are then encoded as operations on a map.

Alternative representation

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.

Some set operations differ slighly. You typically declare…

type void struct{}
var member void

…and do the following:

Operation Code
Create empty set

mySet := make(map[string]bool)

Add an element

mySet["Foo"] = true

Remove an element

delete(mySet, "Foo")

Iterate over a set

for e := range mySet { fmt.Println(e) }

Size of set

size := len(mySet)

Check containment

exists := mySet["Foo"]

Operation Code
Create empty set

mySet := make(map[string]void)

Add an element

mySet["Foo"] = member

Remove an element

delete(mySet, "Foo")

Iterate over a set

for e := range mySet { fmt.Println(e) }

Size of set

size := len(mySet)

Check containment

_, exists := mySet["Foo"]

Comments

Be the first to comment!