~/Using Zero Value Sets in Golang

Mar 15, 2019


In Go, there is no built-in set type, but you can use a map with a bool value as a set. The zero value of such a map is nil, meaning it is uninitialized but still safe for reading.

Example:

1
2
3
4
var mySet map[string]bool
if mySet["foo"] {
    // Will not panic, returns false
}

Adding items requires initialization:

1
2
mySet = make(map[string]bool)
mySet["foo"] = true

Use map for simple sets. Remember that writing to or deleting from a nil map panics; only reading is safe.

If you need a custom Set type, you can wrap a map in a struct.

1
2
3
4
5
type Set map[string]struct{}

func (s Set) Add(item string) {
    s[item] = struct{}{}
}

Check existence:

1
2
3
if _, ok := mySet["foo"]; ok {
    // Found in set
}

For efficient, idiomatic sets in Go, use map keys and avoid non-ASCII data in key strings to match Go best practices.

Tags: [golang] [set] [zerovalue]