简体   繁体   中英

Check if a value exists in a map in Golang

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 :)

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. Like map[valueType]int . Then:

for k, v := range m {
    values[v]++
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM