Go – Implementing a Set

Java, Python and many other languages have many standard collections available, 3 of the most basic and common would be Lists, Maps and Sets. Go provides lists (slices), and maps (dictionaries), but not set. This might seem a deficiency in the language, and while I don’t know the definitive reason, I suspect it’s to do with the ethos of keeping the language small and compact. A set is a very useful collection and even though there isn’t one, it’s functionality can easily be reproduced using a dictionary. Both a dictionary and a set will not allow duplicates, in the case of a dictionary, that is no duplicate keys and this is how a dictionary can be used as a set.

// Create a dictionary of the type required for the set, and a bool
set := make(map[int]bool)

// Add item - adding multiple items with the same key has no adverse affect,
// only one element per key will be present - a map and set share this behaviour
set[1] = true

// Check if 'set' contains an item
_, present := set[1]
fmt.Println(set)

// Delete item - use Go's inbuilt delete function to remove the key
delete(set, 1)
fmt.Println(set)

This is easy enough to use, and additional behaviours found in a set can also be replicated. As an easy reusable option on larger projects, it may be desirable to create a set struct to encapsulate the functionality.

A Simple Set Struct

type Set struct {
   elements map[int]bool
}

// Initialise a new Set
func (set *Set) New() {
   set.elements = make(map[int]bool)
}

// Add a new element to the set
func (set *Set) Add(element int) {
   if !set.Contains(element) {
      set.elements[element] = true
   }
}

// Check is set contains element
func (set *Set) Contains(element int) bool {
   _, exists := set.elements[element]
   return exists
}

// Remove an element from the set, if present
func (set *Set) Delete(element int) {
   delete(set.elements, element)
}

Example Usage

func main() {
  var set *Set
  set = &Set{}
  set.New()

  set.Add(1)
  set.Add(1)
  set.Add(2)
  set.Delete(2)

  fmt.Println(set)
}