You can use map[string]bool as a set. When testing and the absence of a key on the map, a zero value is returned for bool , which is false .
So, fill the map with valid values as keys and true as a value. If the verified key value is on the map, then its stored true value will be the result. If the verified key value is not on the map, returns a zero value for the value type, which is false .
Using this, the test becomes so simple:
valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true} if valid[x] { fmt.Println("found") } else { fmt.Println("not found") }
Try it on the Go Playground (with the options below).
This is stated in a blog post: Go Maps in Action: Using Zero Values
Note:
If you have many valid values, since all the values that should be stored on the map are true , it may be more compact to use a slice to display valid values and use a for range loop to initialize your map, something like this:
for _, v := range []string{"red", "green", "yellow", "blue"} { valid[v] = true }
Note # 2:
If you do not want to go with the initialization of the for range loop, you can optimize it a bit by creating a single-type (or bool type) single-letter const :
const t = true valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}