go-cmp|go-cmp reflect.DeepEqual Slice Failure
单测是遇到对比两个slice时, 因为元素是无序的, 导致相等的item, 判断失败
代码如下:
package mainimport (
"fmt"
"github.com/google/go-cmp/cmp"
)
type Item struct {
Media string
Sizeint64
}
func main() {
standard := []Item{
Item{
Media: "SSD",
Size:100,
},
Item{
Media: "HDD",
Size:200,
},
}
test1 := []Item{
Item{
Media: "HDD",
Size:200,
},
Item{
Media: "SSD",
Size:100,
},
}
fmt.Println(cmp.Equal(standard, test1)) // false
}
期望是: true, 但是实际: false
【go-cmp|go-cmp reflect.DeepEqual Slice Failure】cmp的Equal方法提供了 opts自定义函数
trans := cmp.Transformer(
"Sort",
func(in []Item) []Item {
sort.Slice(
in,
func(i, j int) bool {
return in[i].Size < in[j].Size
})
return in
}) fmt.Println(cmp.Equal(standard, test1,trans)) // true
推荐阅读
- Go|Go Quiz: 从Go面试题搞懂slice range遍历的坑
- [LeetCode]|[LeetCode] 413. Arithmetic Slices
- go 当参数是slice,传值还是传指针()
- js中push、pop、slice、map 和 reduce实现
- Go|Go Quiz: 从Go面试题看slice的底层原理和注意事项
- Go切片基础知识
- 彻底理解Golang Slice
- golang|slice的浅拷贝和深拷贝
- 处理tuple|处理tuple indices must be integers or slices, not str
- golang 转换slice/array 变成xxx,yyy,zzz 【带逗号的字符串】