Skip to content

Instantly share code, notes, and snippets.

@arnehormann
Created May 28, 2014 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnehormann/5810b06517d8aea0c82a to your computer and use it in GitHub Desktop.
Save arnehormann/5810b06517d8aea0c82a to your computer and use it in GitHub Desktop.
func Path(v interface{}, ks ...interface{}) (reflect.Value, error) {
val := reflect.ValueOf(v)
for i, k := range ks {
switch key := k.(type) {
case string: // struct field
if val.Kind() != reflect.Struct {
return reflect.ValueOf(nil), fmt.Errorf("Error at %v[%d]: must be struct", ks, i)
}
val = val.FieldByName(key)
case reflect.Kind: // type
if val.Kind() != key {
return reflect.ValueOf(nil), fmt.Errorf("Error at %v[%d]: must be %s", ks, i, key)
}
switch key {
case reflect.Array, reflect.Slice, reflect.Chan, reflect.Ptr:
val = val.Elem()
default:
return reflect.ValueOf(nil), fmt.Errorf("Error at %v[%d]: must be %s", ks, i, key)
}
default:
return reflect.ValueOf(nil), fmt.Errorf("Error at %v[%d]: must be %s", ks, i, key)
}
if i == len(ks)-1 {
break
}
}
return val, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment