Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions libs/dyn/convert/to_typed.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ func ToTyped(dst any, src dyn.Value) error {
func toTypedStruct(dst reflect.Value, src dyn.Value) error {
switch src.Kind() {
case dyn.KindMap:
// Zero the destination struct such that fields
// that aren't present in [src] are cleared.
dst.SetZero()

info := getStructInfo(dst.Type())
for k, v := range src.MustMap() {
index, ok := info.Fields[k]
Expand Down
21 changes: 21 additions & 0 deletions libs/dyn/convert/to_typed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,27 @@ func TestToTypedStructOverwrite(t *testing.T) {
assert.Equal(t, "baz", out.Bar)
}

func TestToTypedStructClearFields(t *testing.T) {
type Tmp struct {
Foo string `json:"foo"`
Bar string `json:"bar,omitempty"`
}

// Struct value with non-empty fields.
var out = Tmp{
Foo: "baz",
Bar: "qux",
}

// Value is an empty map.
v := dyn.V(map[string]dyn.Value{})

// The previously set fields should be cleared.
err := ToTyped(&out, v)
require.NoError(t, err)
assert.Equal(t, Tmp{}, out)
}

func TestToTypedStructAnonymousByValue(t *testing.T) {
type Bar struct {
Bar string `json:"bar"`
Expand Down