【问题标题】:Go structs comparison - reflect.DeepEqual fails on maps?Go 结构比较 - reflect.DeepEqual 在地图上失败?
【发布时间】:2019-07-16 12:54:59
【问题描述】:

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

【问题讨论】:

标签: go


【解决方案1】:

这里的问题是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 编组细节的知识。
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多