Skip to content

Commit 4663607

Browse files
frozzarekisielk
authored andcommitted
Add support for nested struct pointers #87 (#92)
* Add support for nested struct pointers #87 * Add comment about struct pointers * Add inner struct pointer nil test * Add isValidStructPointer function * Add omitempty test
1 parent 9fa3b6a commit 4663607

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

encoder.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ func (e *Encoder) SetAliasTag(tag string) {
4040
e.cache.tag = tag
4141
}
4242

43+
// isValidStructPointer test if input value is a valid struct pointer.
44+
func isValidStructPointer(v reflect.Value) bool {
45+
return v.Type().Kind() == reflect.Ptr && v.Elem().IsValid() && v.Elem().Type().Kind() == reflect.Struct
46+
}
47+
4348
func isZero(v reflect.Value) bool {
4449
switch v.Kind() {
4550
case reflect.Func:
@@ -80,6 +85,12 @@ func (e *Encoder) encode(v reflect.Value, dst map[string][]string) error {
8085
continue
8186
}
8287

88+
// Encode struct pointer types if the field is a valid pointer and a struct.
89+
if isValidStructPointer(v.Field(i)) {
90+
e.encode(v.Field(i).Elem(), dst)
91+
continue
92+
}
93+
8394
encFunc := typeEncoder(v.Field(i).Type(), e.regenc)
8495

8596
// Encode non-slice types and custom implementations immediately.

encoder_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,25 @@ func TestEncoderWithOmitempty(t *testing.T) {
375375
valsExist(t, "f09", []string{"test"}, vals)
376376
}
377377

378+
type E6 struct {
379+
F01 *inner
380+
F02 *inner
381+
F03 *inner `schema:",omitempty"`
382+
}
383+
384+
func TestStructPointer(t *testing.T) {
385+
vals := map[string][]string{}
386+
s := E6{
387+
F01: &inner{2},
388+
}
389+
390+
encoder := NewEncoder()
391+
encoder.Encode(&s, vals)
392+
valExists(t, "F12", "2", vals)
393+
valExists(t, "F02", "null", vals)
394+
valNotExists(t, "F03", vals)
395+
}
396+
378397
func TestRegisterEncoderCustomArrayType(t *testing.T) {
379398
type CustomInt []int
380399
type S1 struct {

0 commit comments

Comments
 (0)