Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve defaults for zero initialised structs as well #442

Merged
merged 1 commit into from
Jul 30, 2024
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
12 changes: 8 additions & 4 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -989,18 +989,22 @@ func (d *Decoder) createDecodedNewValue(
return newValue, nil
}
}
var newValue reflect.Value
if node.Type() == ast.NullType {
return reflect.Zero(typ), nil
newValue = reflect.New(typ).Elem()
} else {
newValue = d.createDecodableValue(typ)
}
newValue := d.createDecodableValue(typ)
for defaultVal.Kind() == reflect.Ptr {
defaultVal = defaultVal.Elem()
}
if defaultVal.IsValid() && defaultVal.Type().AssignableTo(newValue.Type()) {
newValue.Set(defaultVal)
}
if err := d.decodeValue(ctx, newValue, node); err != nil {
return newValue, errors.Wrapf(err, "failed to decode value")
if node.Type() != ast.NullType {
if err := d.decodeValue(ctx, newValue, node); err != nil {
return newValue, errors.Wrapf(err, "failed to decode value")
}
}
return newValue, nil
}
Expand Down
25 changes: 25 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3027,3 +3027,28 @@ func TestMapKeyCustomUnmarshaler(t *testing.T) {
t.Fatalf("expected to have value \"value\", but got %q", val)
}
}

func TestDecoderPreservesDefaultValues(t *testing.T) {
type nested struct {
Val string `yaml:"val"`
}

type test struct {
First string `yaml:"first"`
Default nested `yaml:"nested"`
}

yml := `
first: "Test"
nested:
# Just some comment here
# val: "default"
`
v := test{Default: nested{Val: "default"}}
if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
t.Fatal(err)
}
if v.Default.Val != "default" {
t.Fatal("decoder doesn't preserve struct defaults")
}
}
Loading