-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c22e343
commit 23cc8f6
Showing
6 changed files
with
78 additions
and
29 deletions.
There are no files selected for viewing
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
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package reflection | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"reflect" | ||
) | ||
|
||
func GetField(obj interface{}, name string) (interface{}, error) { | ||
if !hasValidType(obj, []reflect.Kind{reflect.Struct, reflect.Ptr}) { | ||
return nil, errors.New("Cannot use GetField on a non-struct interface") | ||
} | ||
|
||
objValue := reflectValue(obj) | ||
field := objValue.FieldByName(name) | ||
if !field.IsValid() { | ||
return nil, fmt.Errorf("No such field: %s in obj", name) | ||
} | ||
|
||
return field.Interface(), nil | ||
} | ||
|
||
func hasValidType(obj interface{}, types []reflect.Kind) bool { | ||
for _, t := range types { | ||
if reflect.TypeOf(obj).Kind() == t { | ||
return true | ||
} | ||
} | ||
|
||
return false | ||
} | ||
|
||
func reflectValue(obj interface{}) reflect.Value { | ||
var val reflect.Value | ||
|
||
if reflect.TypeOf(obj).Kind() == reflect.Ptr { | ||
val = reflect.ValueOf(obj).Elem() | ||
} else { | ||
val = reflect.ValueOf(obj) | ||
} | ||
|
||
return val | ||
} |
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