Skip to content

Instantly share code, notes, and snippets.

@mattyw
Created August 28, 2013 20:58
Show Gist options
  • Save mattyw/6371179 to your computer and use it in GitHub Desktop.
Save mattyw/6371179 to your computer and use it in GitHub Desktop.
A go equivalent of clojure's get-in function. Query a nested map with a list of keys
package main
import (
"fmt"
)
func getIn(i interface{}, keys []string) interface{} {
if len(keys) == 0 {
return i
}
if m, ok := i.(map[string]interface{}); ok {
return getIn(m[keys[0]], keys[1:])
}
return nil
}
func main() {
m := map[string]interface{}{
"A": map[string]interface{}{
"B": map[string]interface{}{
"C": 1,
},
},
}
fmt.Println(m)
fmt.Println(getIn(m, []string{"A"}))
fmt.Println(getIn(m, []string{"A", "B"}))
fmt.Println(getIn(m, []string{"A", "B", "C"}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment