go-cmp reflect.DeepEqual Slice F
2019-12-15 本文已影响0人
allenhaozi
单测是遇到对比两个slice时, 因为元素是无序的, 导致相等的item, 判断失败
代码如下:
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
type Item struct {
Media string
Size int64
}
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
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