Hey @gekkonier. I just threw this together for you on https://play.golang.org.
I like @geosoft1’s answer for you but also thought you might like a different method as well that doesn’t necessarily require you to have to do any map reversals and thought that if you’d like to separate being able to search a map using keys and/or values, here’s a simple way for you to help get your head around doing that.
Here’s the playground link. https://play.golang.org/p/4c3UgqNHTZ.
Edit: As a side note, both @geosoft1’s method and my own will only return the first value found in the map. Generally map keys can’t be duplicates, however map values can. Therefore if you need something that returns all values found and not just the first value it finds (if searching by value and not by key), you can just let me know and I can change the code to make that work for you.
I’ll also paste the code here in case you just want a quick look:
package main
import "fmt"
func main() {
// Create a new map m.
m := map[string]string{
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
}
// Find in map by value
fmt.Println(findByValue(m, "1"))
fmt.Println(findByValue(m, "10"))
// Find in map by key
fmt.Println(findByKey(m, "one"))
fmt.Println(findByKey(m, "ten"))
// Generic find in map. Searches using keys and values.
fmt.Println(findInMap(m, "five"))
fmt.Println(findInMap(m, "5"))
fmt.Println(findInMap(m, "twenty"))
fmt.Println(findInMap(m, "20"))
}
// findInMap uses findByValue and findByKey to check whether a
// string exists either as a key or a value inside of a map.
//
// findInMap returns either the key or value, if the string was found
// in the map, or an empty string if neither were found.
func findInMap(m map[string]string, str string) string {
// Check if str exists as a value in map m.
if val := findByKey(m, str); val != "" {
return val
}
// Check if str exists as a key in map m.
if val := findByValue(m, str); val != "" {
return val
}
// str doesn't exist in map m.
return ""
}
// findByValue searches for a string in a map based on map values.
//
// findByValue returns the key if the value was found, or an empty
// string if it wasn't.
func findByValue(m map[string]string, value string) string {
for key, val := range m {
if val == value {
return key
}
}
return ""
}
// findByKey searches for a string in a map based on map keys.
//
// findByKey returns the value if the key was found, or an empty
// string if it wasn't.
func findByKey(m map[string]string, key string) string {
if val, found := m[key]; found {
return val
}
return ""
}
Let me know if you have any questions!