Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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