我正在编写单元测试,我的目标是将数据从 json 解码到一个结构并将其与另一个模拟结构进行比较。我正在使用 reflect.DeepEqual() 方法,但它在这些方法上返回 false。
我的猜测是它与在后台进行的类型转换有某种关系,其中 map[string]interface{} 被转换为 map[string]int,但据我所知。
type MyStruct struct {
Cache map[string]interface{} `json:"cache"`
}
var js = `{"cache":{"productsCount":28}}`
func main() {
var s1, s2 MyStruct
s1 = MyStruct{
Cache: map[string]interface{} {
"productsCount": 28,
},
}
s2 = MyStruct{}
err := json.Unmarshal([]byte(js), &s2)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%#v\n", s1)
fmt.Printf("%#v\n", s2)
fmt.Println(reflect.DeepEqual(s1, s2))
}
输出看起来像这样:
main.MyStruct{Cache:map[string]interface {}{"productsCount":28}}
main.MyStruct{Cache:map[string]interface {}{"productsCount":28}}
false
最佳答案
这里的事情是 golang 如何编码 int
,你将它初始化为 int
,但在你提供的 json 中它是 float64
.
这是工作示例:
package main
import (
"encoding/json"
"fmt"
"os"
"reflect"
)
type MyStruct struct {
Cache map[string]interface{} `json:"cache"`
}
var js = `{"cache":{"productsCount":28}}`
func main() {
var s1, s2 MyStruct
s1 = MyStruct{
Cache: map[string]interface{}{
"productsCount": float64(28),
},
}
s2 = MyStruct{}
err := json.Unmarshal([]byte(js), &s2)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%#v\n", s1)
fmt.Printf("%#v\n", s2)
fmt.Println(reflect.DeepEqual(s1, s2))
}
输出:
main.MyStruct{Cache:map[string]interface {}{"productsCount":28}}
main.MyStruct{Cache:map[string]interface {}{"productsCount":28}}
true
关于Go 结构比较 - reflect.DeepEqual 在 map 上失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57057773/