Go结构体比较 - reflect.DeepEqual在比较map时失败?

3
我正在编写单元测试,我的目标是将数据从 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

可能是重复的问题:如何比较结构体、切片、映射是否相等? - Vikash Pathak
1
我不认为这是重复的,那个帖子更加通用。 - IFeel3
1个回答

9

问题在于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

谢谢,这正是我需要的解释。我之前缺乏有关JSON编组细节的知识。 - IFeel3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接