为了账号安全,请及时绑定邮箱和手机立即绑定

为什么这些看似相同的 Golang 结构不相等?

为什么这些看似相同的 Golang 结构不相等?

Go
一只甜甜圈 2022-05-10 13:33:22
我正在尝试学习 Golang 测试。我正在比较 2 个看似相同的结构,但它们并不相等。出了什么问题?2020/01/22 17:10:10 ****2 cities[0] is type *main.City has &main.City{Name:"Boston", State:"", Country:"USA", Capital:true, Population:685000} 2020/01/22 17:10:10 ****2 expected  is type *main.City has &main.City{Name:"Boston", State:"", Country:"USA", Capital:true, Population:685000} 2020/01/22 17:10:11 Preparing to DELETE 5 city docs--- FAIL: TestCities (3.08s)    --- FAIL: TestCities/Test_POST_should_add_New_City (0.62s)        city_handlers_test.go:68: Why is ( cities[0] != expected )Boston was not added to Firestore:              got &{Boston  USA true 685000}               want &{Boston  USA true 685000}FAILexit status 1这是测试:        // why don't these structs match?        log.Printf("****2 cities[0] is type %T has %#v \n", cities[0], cities[0])        log.Printf("****2 expected  is type %T has %#v \n", expected, expected)        // why is this comparison failing when both are the same type with the same values?        if cities[0] != expected {            t.Errorf("Why is ( cities[0] != expected )Boston was not added to Firestore: \n got %v  \n want %v", cities[0], expected)        }
查看完整描述

1 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

您比较指针,看起来它们指向不同的对象。为了正确检查,您应该比较对象的字段。

这个包可以帮助你做到这一点:reflect.DeepEqual()testify.EqualValues()cmp.Equal()

示例: https: //play.golang.org/p/09BYFeYj5xx


查看完整回答
反对 回复 2022-05-10
  • 1 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号