Skip to content

Commit a1d01f8

Browse files
committed
Add support for decoding into concreet structs
The codegen changes means we need to support decoding data into concreet structs, and not just pointers to structs.
1 parent 654e553 commit a1d01f8

File tree

2 files changed

+31
-15
lines changed

2 files changed

+31
-15
lines changed

pkl/decode_struct.go

+24-8
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,15 @@ func getStructFields(typ reflect.Type) map[string]structField {
306306
field := typ.Field(i)
307307
// embedded
308308
if field.Anonymous {
309-
for k, v := range getStructFields(field.Type.Elem()) {
310-
ret[k] = v
309+
switch field.Type.Kind() {
310+
case reflect.Ptr:
311+
for k, v := range getStructFields(field.Type.Elem()) {
312+
ret[k] = v
313+
}
314+
case reflect.Struct:
315+
for k, v := range getStructFields(field.Type) {
316+
ret[k] = v
317+
}
311318
}
312319
} else {
313320
opts := parseStructOpts(&field)
@@ -328,13 +335,22 @@ func (d *decoder) getOutputValue(typ reflect.Type) (*reflect.Value, error) {
328335
for i := 0; i < numFields; i++ {
329336
field := typ.Field(i)
330337
if field.Anonymous {
331-
fieldValue := reflect.New(field.Type.Elem())
332-
// Assertion: all embedded fields are pointers to structs.
333-
structValue, err := d.getOutputValue(field.Type.Elem())
334-
if err != nil {
335-
return nil, err
338+
var fieldValue reflect.Value
339+
switch field.Type.Kind() {
340+
case reflect.Ptr:
341+
{
342+
fieldValue = reflect.New(field.Type.Elem())
343+
structValue, err := d.getOutputValue(field.Type.Elem())
344+
if err != nil {
345+
return nil, err
346+
}
347+
fieldValue.Elem().Set(*structValue)
348+
}
349+
case reflect.Struct:
350+
{
351+
fieldValue = reflect.New(field.Type).Elem()
352+
}
336353
}
337-
fieldValue.Elem().Set(*structValue)
338354
ret.FieldByName(field.Name).Set(fieldValue)
339355
}
340356
}

pkl/unmarshal_test.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -310,29 +310,29 @@ func TestUnmarshal_Dynamic(t *testing.T) {
310310

311311
func TestUnmarshal_Classes(t *testing.T) {
312312
expected := classes.Classes{
313-
Animals: []classes.Animal{
314-
&classes.GreyhoundImpl{
315-
DogImpl: &classes.DogImpl{
313+
Animals: []classes.IAnimal{
314+
&classes.Greyhound{
315+
Dog: classes.Dog{
316316
Name: "Uni",
317317
Barks: false,
318318
Breed: "Greyhound",
319319
},
320320
CanRoach: true,
321321
},
322-
&classes.CatImpl{
322+
&classes.Cat{
323323
Name: "Millie",
324324
Meows: true,
325325
},
326326
},
327-
MyAnimal: &classes.GreyhoundImpl{
328-
DogImpl: &classes.DogImpl{
327+
MyAnimal: &classes.Greyhound{
328+
Dog: classes.Dog{
329329
Name: "Uni",
330330
Barks: false,
331331
Breed: "Greyhound",
332332
},
333333
CanRoach: true,
334334
},
335-
House: &classes.House{
335+
House: classes.House{
336336
Area: 2000,
337337
Bedrooms: 3,
338338
Bathrooms: 2,

0 commit comments

Comments
 (0)