Quidest?

Use a map to represent a set in Go

· Lorenzo Drumond

When you want to represent a set of objects in Go, a nice trick is to use a map with keys as your objects, and values as booleans.

E.g.:

1var myMap = map[Object]bool{
2  Object1: true,
3  Object2: true,
4  Object3: true,
5  ...,
6}

This will make it very natural when checking the existence of an object in your set:

1if myMap[obj] {
2  ...
3}

in fact, if the object doesn’t exist, by default Go returns the empty value ([non-existent-keys-in-go-maps]]), which for booleans is false ([zero-values-and-default-values-in-go, which for booleans is false ([[zero-values-and-default-values-in-go/))

References

#set #map #programming #booleans #values #variables #golang