gpt4 book ai didi

go - 这些看似相同的Golang结构为何不相等?

转载 作者:行者123 更新时间:2023-12-01 22:32:52 24 4
gpt4 key购买 nike

我正在尝试学习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}
FAIL
exit 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)
}

最佳答案

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

该软件包可以帮助您做到这一点:reflect.DeepEqual()testify.EqualValues()cmp.Equal()

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

关于go - 这些看似相同的Golang结构为何不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59869104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com