Created
May 28, 2014 15:42
-
-
Save arnehormann/5810b06517d8aea0c82a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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