Skip to content

Commit 2c80bd3

Browse files
committed
Map nested struct pointers
1 parent 208dff5 commit 2c80bd3

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

record.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -654,10 +654,15 @@ func (r *Record) Map(obj interface{}, timeLoc *time.Location) {
654654
field.Set(reflect.ValueOf(r.Time(tag, timeLoc)))
655655
}
656656

657-
//Map nested structs
657+
//Nested structs
658658
if field.Kind() == reflect.Struct {
659+
//Map nested struct
659660
r.Map(field.Addr().Interface(), timeLoc)
660661
continue
662+
} else if field.Kind() == reflect.Pointer && field.Elem().Kind() == reflect.Struct {
663+
//Map nested pointer to struct
664+
r.Map(field.Interface(), timeLoc)
665+
continue
661666
}
662667
}
663668
}

record_test.go

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,10 @@ func newTestRecord() Record {
4444
)
4545
}
4646

47+
type nestedStructPointer struct {
48+
String string `fm:"string"`
49+
}
50+
4751
type testRecordStruct struct {
4852
String string `fm:"string"`
4953
Int int `fm:"int"`
@@ -70,6 +74,8 @@ type testRecordStruct struct {
7074
String string `fm:"string_2"`
7175
}
7276
}
77+
NestedStructPointer *nestedStructPointer
78+
NestedNilStructPointer *nestedStructPointer
7379
}
7480

7581
//TestRecordMap tests the `Record.Map` method
@@ -79,6 +85,7 @@ func TestRecordMap(t *testing.T) {
7985

8086
//Create a struct to map the dummy record to
8187
var value testRecordStruct
88+
value.NestedStructPointer = &nestedStructPointer{}
8289

8390
//Map the dummy record to the struct
8491
record.Map(&value, time.UTC)
@@ -239,15 +246,30 @@ func TestRecordMap(t *testing.T) {
239246
got := value.Nested.String
240247
expect := "related"
241248
if got != expect {
242-
t.Errorf("got: %v, expected: %v", got, expect)
249+
t.Errorf("got: '%v', expected: '%v'", got, expect)
243250
}
244251
})
245252

246253
t.Run("nested_nested_string", func(t *testing.T) {
247254
got := value.Nested.Nested.String
248255
expect := "string2"
249256
if got != expect {
250-
t.Errorf("got: %v, expected: %v", got, expect)
257+
t.Errorf("got: '%v', expected: '%v'", got, expect)
258+
}
259+
})
260+
261+
t.Run("nested_pointer_string", func(t *testing.T) {
262+
got := value.NestedStructPointer.String
263+
expect := "string"
264+
if got != expect {
265+
t.Errorf("got: '%v', expected: '%v'", got, expect)
266+
}
267+
})
268+
269+
t.Run("nested_nil_pointer", func(t *testing.T) {
270+
got := value.NestedNilStructPointer
271+
if got != nil {
272+
t.Errorf("got: %v, expected: %v", got, nil)
251273
}
252274
})
253275
}

0 commit comments

Comments
 (0)