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

    推荐阅读