Check if the value is in the list

Is there something similar to the Python in keyword? I want to check if there is a value in the list.

For example, in Python:

 x = 'red' if x in ['red', 'green', 'yellow', 'blue']: print "found" else: print "not found" 

In Go, I came up with a set of idioms, but I don’t think it is ideal, since I have to specify an int value that I don’t use.

 x := "red" valid := map[string]int{"red": 0, "green": 0,"yellow": 0, "blue": 0} if _, ok := valid[x]; ok { fmt.Println("found") } else { fmt.Println("not found") } 

I understand that the in keyword is probably related to generics. Is there a way to do this using "generate" or something else?

+5
source share
1 answer

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} 
+11
source

All Articles