From ab1f877b3c3a0a347fa304d5297b500c9de85a63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 8 Mar 2024 15:51:38 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=AD=97=E7=AC=A6=E4=B8=B2?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E7=9A=84=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tool/define/diff.go | 29 +++++++++++++++++------------ tool/define/diff_test.go | 1 + 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/tool/define/diff.go b/tool/define/diff.go index 5b9d50a..8b63d9e 100644 --- a/tool/define/diff.go +++ b/tool/define/diff.go @@ -21,7 +21,8 @@ import ( // // Date : 11:12 2024/3/8 type DiffOption struct { - StrictMode bool `json:"strict_mode"` // 采用严格模式: 1 != "1", 1 != 1.0 , 采用非严格模式 1 == "1", 1 == 1.0 + StrictMode bool `json:"strict_mode"` // 采用严格模式: 1 != 1.0 , 采用非严格模式 1 == 1.0 + AllowStringNumber bool `json:"allow_string_number"` // 是否允许字符串数字, 在非严格模式下, 若允许, 则 1 == "1" , 不允许, 则 1 != "1" IgnoreNotFoundField bool `json:"ignore_not_found_field"` // 忽略不存在的字段 IgnoreEmptyString bool `json:"ignore_empty_string"` // 忽略空字符串, 若输入值为空字符串, 则不做比较, 认为两个值相同 IgnoreZeroNumber bool `json:"ignore_zero_number"` // 忽略置为0的数字, 若输入的数据为数字类型, 则不做比较, 认为两个值相同 @@ -200,20 +201,24 @@ func DefaultDiffFunc(field string, inputVal wrapper.Map, storageVal wrapper.Map, // 存储值尝试转 float64 inputValStr := fmt.Sprintf("%v", inputFieldVal) storageValStr := fmt.Sprintf("%v", storageFieldVal) - var ( - storageFloat64 float64 - inputFloat64 float64 - ) - if err := util.ConvertAssign(&storageFloat64, storageValStr); nil == err { - if err := util.ConvertAssign(&inputFloat64, inputValStr); nil == err { - if storageFloat64 == inputFloat64 { - return result - } - } - } if inputValStr == storageValStr { return result } + if option.AllowStringNumber { + // 允许字符串数字 + var ( + storageFloat64 float64 + inputFloat64 float64 + ) + if err := util.ConvertAssign(&storageFloat64, storageValStr); nil == err { + if err := util.ConvertAssign(&inputFloat64, inputValStr); nil == err { + if storageFloat64 == inputFloat64 { + return result + } + } + } + } + // 浮点型数字. 去小数部分最右侧的0 if inputFieldValType.Kind() == reflect.Float64 || inputFieldValType.Kind() == reflect.Float32 { inputValStrArr := strings.Split(inputValStr, ".") diff --git a/tool/define/diff_test.go b/tool/define/diff_test.go index 1f36560..d805e90 100644 --- a/tool/define/diff_test.go +++ b/tool/define/diff_test.go @@ -43,6 +43,7 @@ func TestDefaultDiffFunc(t *testing.T) { assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与float64相等") res = DefaultDiffFunc("num3", input, storage, diffOption) assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与string相等") + diffOption.AllowStringNumber = true res = DefaultDiffFunc("num4", input, storage, diffOption) assert.EqualValues(t, true, res.IsSame, "非严格模式下, float32与string相等") }