Skip to content

Commit

Permalink
- Adding GetChildElemPtrType API ✨
Browse files Browse the repository at this point in the history
- Adding test for the new API ✅
  • Loading branch information
fairyhunter13 committed Nov 17, 2020
1 parent 0ad96dc commit c7861c7
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
15 changes: 15 additions & 0 deletions type.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,18 @@ func GetChildElemType(val reflect.Value) (typ reflect.Type) {
}
return
}

// GetChildElemPtrType returns the child elem's (root child) ptr type of the val of reflect.Value.
func GetChildElemPtrType(val reflect.Value) (typ reflect.Type) {
if !val.IsValid() {
return
}

typ = val.Type()
res := typ.Kind()
for res == reflect.Ptr {
typ = typ.Elem()
res = typ.Kind()
}
return
}
47 changes: 47 additions & 0 deletions type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,50 @@ func TestGetChildElemType(t *testing.T) {
})
}
}

func TestGetChildElemPtrType(t *testing.T) {
type args struct {
val func() reflect.Value
}
tests := []struct {
name string
args args
wantTyp reflect.Type
}{
{
name: "invalid reflect value",
args: args{
val: func() reflect.Value {
return reflect.ValueOf(nil)
},
},
wantTyp: nil,
},
{
name: "valid slice type",
args: args{
val: func() reflect.Value {
return reflect.ValueOf([]int{1, 2, 3})
},
},
wantTyp: reflect.TypeOf([]int{}),
},
{
name: "valid ptr type",
args: args{
val: func() reflect.Value {
var x **int
return reflect.ValueOf(x)
},
},
wantTyp: reflect.TypeOf(5),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if gotTyp := GetChildElemPtrType(tt.args.val()); !reflect.DeepEqual(gotTyp, tt.wantTyp) {
t.Errorf("GetChildElemPtrType() = %v, want %v", gotTyp, tt.wantTyp)
}
})
}
}

0 comments on commit c7861c7

Please sign in to comment.