Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way of getting key depending on value from hashmap in Golang

Tags:

hashmap

key

go

Given a hashmap in Golang which has a key and a value, what is the simplest way of retrieving the key given the value?

For example Ruby equivalent would be key = hashMap.key(value)

like image 202
hhh Avatar asked Nov 28 '22 14:11

hhh


2 Answers

There is no built-in function to do this; you will have to make your own. Below is an example function that will work for map[string]int, which you can adapt for other map types:

func mapkey(m map[string]int, value int) (key string, ok bool) {
  for k, v := range m {
    if v == value { 
      key = k
      ok = true
      return
    }
  }
  return
}

Usage:

key, ok := mapkey(hashMap, value)
if !ok {
  panic("value does not exist in map")
}
like image 56
Tim Cooper Avatar answered Dec 05 '22 12:12

Tim Cooper


The important question is: How many times will you have to look up the value?

If you only need to do it once, then you can iterate over the key, value pairs and keep the key (or keys) that match the value.

If you have to do the look up often, then I would suggest you make another map that has key, values reversed (assuming all keys map to unique values), and use that for look up.

like image 20
Akavall Avatar answered Dec 05 '22 13:12

Akavall