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

标签 go

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

相关文章:

go - 当golang关闭 channel 时,接收者goroutine永远不会被阻塞

methods - 方法接收者

json.Unmarshal 返回空白结构

bash - 在Circleci中使用golang-ci-lint

windows - 列出在任意PE(EXE)文件中链接的DLL的名称

dictionary - Go 中的索引表达式是否根据上下文更改其返回类型?

go - 如何将命名模板的结果发送到函数

json - 我可以将 JSON 解码为接口(interface)的实现者吗?

go - 在 `go install package` 期间创建一些二进制文件

json - 使用自定义攻击者在 Vegeta 的 POST 请求中发送有效载荷