I am searching for an efficient way to check if a value exists in Golang. The way I know is using a for loop/ range. Is there a better way to do the same?
Any help would be appreciated :)
I am searching for an efficient way to check if a value exists in Golang. The way I know is using a for loop/ range. Is there a better way to do the same?
Any help would be appreciated :)
When you index a map in Go you get two return values; the second one (which is optional) is a boolean that indicates if the key exists.
If the key doesn’t exist, the first value will be the default zero value.
Use second return value directly in an if statement.
m := map[string]float64{"pi": 3.14}
if v, found := m["pi"]; found {
fmt.Println(v)
}
There is no built in way to find out if a map contains a particular value. If you need this behaviour to be efficient, consider using an additional data structure to support it.
Note that although Java's Map
provides containsValue
, the documentation says:
This operation will probably require time linear in the map size for most implementations of the Map interface.
So, if you need an efficient implementation for a Java Map, you also need to provide one.
What "an efficient implementation" means changes based on what kind of data you're mapping. For example, if values are always unique, then maintaining a map[value]key
is enough). If they're not, then something more principled is needed.
If you have rather big map and want to optimize value checking then add one more map nearly. Likemap[valueType]int
. Then:
for k, v := range m {
values[v]++
}