0Pricing
Go Academy · Lesson

Maps as Sets

Use maps for unique values.

Go Has No Set Type

Go does not have a built-in set type. The idiomatic way to model a set of unique values is to use a map where the keys are the set elements.

Map of Bools

One approach: map[string]bool. Presence of a key (and value true) means the element is in the set.

package main

import "fmt"

func main() {
	set := map[string]bool{}
	set["apple"] = true
	set["banana"] = true
	fmt.Println(set)
}

All lessons in this course

  1. Map Internals
  2. Checking Existence
  3. Maps as Sets
  4. Iteration and Ordering
← Back to Go Academy