Skip to content

Commit

Permalink
Add IsNil that won't panic
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfmin committed Apr 21, 2019
1 parent c957e10 commit 4959e02
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions get.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,27 @@ func MustGet(i interface{}, name string) (value interface{}) {
return
}

func IsNil(i interface{}) bool {
v := reflect.ValueOf(i)

switch v.Kind() {
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Interface, reflect.Func, reflect.Chan, reflect.UnsafePointer:
return v.IsNil()
default:
}
return false
}

// Get value of a struct by path using reflect.
func Get(i interface{}, name string) (value interface{}, err error) {
// printv(i, name)

v := reflect.ValueOf(i)

if v.CanSet() && v.IsNil() {
if IsNil(i) {
return
}

v := reflect.ValueOf(i)

if name == "" {
value = v.Interface()
return
Expand Down

0 comments on commit 4959e02

Please sign in to comment.