gpt4 book ai didi

json - 在 golang 中使用 json marshaling 测试深度相等性

转载 作者:IT老高 更新时间:2023-10-28 13:10:10 25 4
gpt4 key购买 nike

鉴于这两个测试用例:

func TestEqualWhat(t *testing.T) {
testMarshalUnmarshal(t, map[string]interface{}{"a":"b"})
testMarshalUnmarshal(t, map[string]interface{}{"a":5})
}

testMarshalUnmarshal 助手只是编码到 json 并退出:

func testMarshalUnmarshal(t *testing.T, in map[string]interface{}) {
//marshal the object to a string
jsb, err := json.Marshal(in);
if err != nil {
log.Printf("Unable to marshal msg")
t.FailNow()
}

//unmarshal to a map
res := make(map[string]interface{})
if err := json.Unmarshal(jsb, &res); err != nil { t.FailNow() }

if !reflect.DeepEqual(in, res) {
log.Printf("\nExpected %#v\nbut got %#v", in, res)
t.FailNow()
}
}

为什么第一个测试用例通过而第二个失败?测试的输出是这样的:

Expected map[string]interface {}{"a":5}
but got map[string]interface {}{"a":5}
--- FAIL: TestEqualWhat (0.00 seconds)

Here is similar code on the go playground这样你就可以轻松破解它了。

最佳答案

我想通了! JSON只有一种数值类型,即 float ,所以在编码/解码过程中,所有整数都会转换为Float64。因此,在 res 映射中,5 是 float64 而不是 int。

Here是一个围棋 Playground ,为我正在谈论的内容提供背景和证据。

关于json - 在 golang 中使用 json marshaling 测试深度相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com