Skip to content

Commit

Permalink
Fix pointer confusion when assigning map to struct
Browse files Browse the repository at this point in the history
The Map was not able to `ReflectTo()` a reflect.Value with kind `Struct`
sinc it assumed that all structs would be sent as pointers. That isn't
the case when the call comes from `FromValue()`.
  • Loading branch information
thallgren committed Aug 25, 2020
1 parent ece592b commit 5671e6f
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
13 changes: 8 additions & 5 deletions internal/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -701,12 +701,15 @@ func (g *hashMap) ReflectTo(value reflect.Value) {
panic(catch.Error(`reflectTo: nil pointer`))
}
ht = ht.Elem()
if ht.Kind() == reflect.Struct {
v := value.Elem()
s := Struct(v, false)
s.PutAll(g)
return
}

if ht.Kind() == reflect.Struct {
if ptr {
value = value.Elem()
}
s := Struct(value, false)
s.PutAll(g)
return
}
if ht.Kind() == reflect.Interface && ht.Name() == `` {
ht = g.Type().ReflectType()
Expand Down
28 changes: 28 additions & 0 deletions internal/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,34 @@ func TestMap_ReflectTo_struct(t *testing.T) {
assert.Panic(t, func() { m.ReflectTo(reflect.ValueOf(sb)) }, `reflectTo: nil pointer`)
}

func TestMap_ReflectTo_structElem(t *testing.T) {
m := vf.Map(
`First`, 1,
`Second`, 2.0,
`Third`, `three`)

type structA struct {
First int
Second float64
}
type structB struct {
structA
Third string
}

sb := &structB{}
m.ReflectTo(reflect.ValueOf(sb).Elem())
assert.Equal(t, 1, sb.First)
assert.Equal(t, 2.0, sb.Second)
assert.Equal(t, `three`, sb.Third)

sb = &structB{}
vf.FromValue(m, sb)
assert.Equal(t, 1, sb.First)
assert.Equal(t, 2.0, sb.Second)
assert.Equal(t, `three`, sb.Third)
}

func TestMap_Remove(t *testing.T) {
mi := vf.Map(
`first`, 1,
Expand Down

0 comments on commit 5671e6f

Please sign in to comment.