From 248a44eb1e2a58e35b2674342d1994a0f7b4a7be Mon Sep 17 00:00:00 2001 From: qiangxue Date: Wed, 12 Jul 2017 16:26:31 -0400 Subject: [PATCH] Fixes #37: Fields in embedded struct should always be shadowed by fields in outer struct --- struct.go | 11 +++++++---- struct_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/struct.go b/struct.go index 5928140..f29775e 100644 --- a/struct.go +++ b/struct.go @@ -188,10 +188,13 @@ func (si *structInfo) build(a reflect.Type, path []int, namePrefix, dbNamePrefix dbName: concat(dbNamePrefix, dbName), path: path2, } - si.nameMap[fi.name] = fi - si.dbNameMap[fi.dbName] = fi - if isPK { - si.pkNames = append(si.pkNames, fi.name) + // a field in an anonymous struct may be shadowed + if _, ok := si.nameMap[fi.name]; !ok || len(path2) < len(si.nameMap[fi.name].path) { + si.nameMap[fi.name] = fi + si.dbNameMap[fi.dbName] = fi + if isPK { + si.pkNames = append(si.pkNames, fi.name) + } } } } diff --git a/struct_test.go b/struct_test.go index 4a839d1..3ec60b9 100644 --- a/struct_test.go +++ b/struct_test.go @@ -92,6 +92,30 @@ func Test_structValue_columns(t *testing.T) { assert.Equal(t, map[string]interface{}{"Name": "abc"}, cols) } +func TestIssue37(t *testing.T) { + customer := Customer{ + ID: 1, + Name: "abc", + Status: 2, + Email: "abc@example.com", + } + ev := struct{ + Customer + Status string + } {customer, "20"} + sv := newStructValue(&ev, nil) + cols := sv.columns([]string{"ID", "Status"}, nil) + assert.Equal(t, map[string]interface{}{"ID": 1, "Status": "20"}, cols) + + ev2 := struct{ + Status string + Customer + } {"20", customer} + sv = newStructValue(&ev2, nil) + cols = sv.columns([]string{"ID", "Status"}, nil) + assert.Equal(t, map[string]interface{}{"ID": 1, "Status": "20"}, cols) +} + type MyCustomer struct{} func Test_getTableName(t *testing.T) {