5

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

4
  • 4
    The question is confusing - you say you want to know if a map contains a value, but you compare to Java's containsKey, which checks if a map contains a key. Which are you looking for? Commented Nov 9, 2017 at 22:22
  • 1
    If you're looking for how to tell that a key exists, the answer is here: stackoverflow.com/questions/2050391/… Commented Nov 9, 2017 at 22:23
  • @Adrian .. Apologies for the confusion. I have edited the question. Commented Nov 9, 2017 at 22:26
  • 1
    @TimothyJones I have the value and check if the value exists in the map and if yes, then extract the key Commented Nov 9, 2017 at 22:27

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If they are not unique, a map[value][]key might work, though it's more effort to maintain.
8

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

Comments

1

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]++
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.