Essential Go Maps  Suggest an edit

Use map as a set

Some languages have a native structure for sets. To make a set in Go, it’s best practice to use a map from the value type of the set to an empty struct (map[Type]struct{}).

For example, with strings:

greetings := map[string]struct{}{
	"hi":    {},
	"hello": {},

// delete a value from set
delete(greetings, "hi")

// add a value to set
greetings["hey"] = struct{}{}

// check if a value is in the set:
if _, ok := greetings["hey"]; ok {
	fmt.Printf("'hey' is in greetings\n")
'hey' is in greetings

  ↑ ↓ to navigate     ↵ to select     Esc to close