Skip to content

Commit

Permalink
use IsNil to convert result to normal nil
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfmin committed Apr 21, 2019
1 parent d7d7515 commit c957e10
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
10 changes: 7 additions & 3 deletions get.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ func MustGet(i interface{}, name string) (value interface{}) {
func Get(i interface{}, name string) (value interface{}, err error) {
// printv(i, name)

if name == "" {
value = i
v := reflect.ValueOf(i)

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

v := reflect.ValueOf(i)
if name == "" {
value = v.Interface()
return
}

var token *dotToken
token, err = nextDot(name)
Expand Down
8 changes: 8 additions & 0 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,11 @@ func TestGet(t *testing.T) {
panic(fmt.Sprintf("expected is %v, but was %v", c1.Name, p.Company.Name))
}
}

func TestGetNil(t *testing.T) {
p := &Person{}
c := MustGet(p, "Company")
if c != nil {
t.Error("Get field nil should be nil")
}
}

0 comments on commit c957e10

Please sign in to comment.