MarkJoyMa 2 years ago committed by Kevin Wan
parent ba771f8ff1
commit 142c46228b

@ -32,7 +32,8 @@ type fieldInfo struct {
mapField *fieldInfo
}
// FillDefault fills the default values for the given v.
// FillDefault fills the default values for the given v,
// and the premise is that the value of v must be guaranteed to be empty
func FillDefault(v any) error {
return fillDefaultUnmarshaler.Unmarshal(map[string]any{}, v)
}

@ -1078,4 +1078,16 @@ func TestFillDefaultUnmarshal(t *testing.T) {
assert.Equal(t, st.A, "a")
assert.Equal(t, st.C, "c")
})
t.Run("has vaue", func(t *testing.T) {
type St struct {
A string `json:",default=a"`
B string
}
var st = St{
A: "b",
}
err := FillDefault(&st)
assert.Error(t, err)
})
}

@ -711,7 +711,14 @@ func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect
valuer := createValuer(m, opts)
mapValue, hasValue := getValue(valuer, canonicalKey)
if !hasValue || u.opts.fillDefault {
// When fillDefault is used, m is a null value, hasValue must be false, all priority judgments fillDefault,
if u.opts.fillDefault {
if !value.IsZero() {
return fmt.Errorf("set the default value, %s must be zero", fullName)
}
return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName)
} else if !hasValue {
return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName)
}

@ -4425,4 +4425,16 @@ func TestFillDefaultUnmarshal(t *testing.T) {
assert.Equal(t, st.A, "a")
assert.Equal(t, st.C, "c")
})
t.Run("has value", func(t *testing.T) {
type St struct {
A string `json:",default=a"`
B string
}
var st = St{
A: "b",
}
err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st)
assert.Error(t, err)
})
}

Loading…
Cancel
Save