I have a fairly long else if chain looking for keys in a map and setting a specific value if found. The way I chose to do it with the least amount of code was this (m
is a map[string]interface{}
)
var ok bool
var s interface{}
if s, ok = m["key1"]; ok {
} else if s, ok = m["key2"]; ok {
....
} else if s, ok = m["keyN"]; ok {
} else {
return RuhRohError
}
g.Id = s.(string)
This feels kinda clunky, I am doing all of these else if
's to set a variable in the condition. Is there an idiomatic way to do this? I think this way doesn't make it immediately obvious what I am trying to do.
For example,
package main
import "fmt"
func findValue(m map[string]interface{}, keys []string) (interface{}, bool) {
for _, key := range keys {
if value, ok := m[key]; ok {
return value, true
}
}
return nil, false
}
func main() {
m := map[string]interface{}{"keyn": "valuen"}
keys := []string{"key1", "key2", "keyn"}
s, found := findValue(m, keys)
if !found {
return
}
id := s.(string)
fmt.Println(id)
}
Output:
valuen
Actually I think the code you provided is very easy to read and understand. It is a bit verbose but there is no magic ;). So if there is only one place where you have to write this code I would leave it as it is. If you need to write it a few times I would consider writing findValue
function mentioned in another comment.