SortSlicesだと子インスタンスで持つ値がバラバラの場合、無視することが出来ないがTransformerだと出来る。
NumSlice構造体で持つNumsの順番がバラバラな構造体を作る。
func TestSortSlice5(t *testing.T) {
type NumSlice struct {
Id int
Nums []int
}
type Compare struct {
NumSlice NumSlice
}
v1 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{1, 2, 3, 4, 5}}, // 昇順
}
v2 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{5, 4, 3, 2, 1}}, // 降順
}
opts := []cmp.Option{
cmp.Transformer("NumSlice", func(in []int) []int {
out := append([]int(nil), in...) // Copy input to avoid mutating it
sort.Ints(out)
return out
}),
}
if diff := cmp.Diff(v1, v2, opts...); diff != "" {
t.Errorf("Compare value is mismatch (-v1 +v2):%s\n", diff)
}
}
親構造体に文字列のスライスを追加してみる
func TestSortSlice(t *testing.T) {
type NumSlice struct {
Id int
Nums []int
}
type Compare struct {
NumSlice NumSlice
StringSlice []string
}
v1 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{1, 2, 3, 4, 5}}, // 昇順
StringSlice: []string{"1", "2", "3"}, // 昇順
}
v2 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{5, 4, 3, 2, 1}}, // 降順
StringSlice: []string{"3", "2", "1"}, // 降順
}
// 文字列スライス用を追加
opts := []cmp.Option{
cmp.Transformer("NumSlice", func(in []int) []int {
out := append([]int(nil), in...) // Copy input to avoid mutating it
sort.Ints(out)
return out
}),
cmp.Transformer("StringSlice", func(in []string) []string {
out := append([]string(nil), in...) // Copy input to avoid mutating it
sort.Strings(out)
return out
}),
}
if diff := cmp.Diff(v1, v2, opts...); diff != "" {
t.Errorf("Compare value is mismatch (-v1 +v2):%s\n", diff)
}
}
正しく比較がされているか、異なる値を入れてみる。
func TestSortSlice(t *testing.T) {
type NumSlice struct {
Id int
Nums []int
}
type Compare struct {
NumSlice NumSlice
StringSlice []string
}
v1 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{1, 2, 3, 4, 5}},
StringSlice: []string{"1", "2", "3", "4"}, // 3番目に"4"を追加
}
v2 := &Compare{
NumSlice: NumSlice{Id: 1, Nums: []int{5, 4, 3, 2, 1}},
StringSlice: []string{"5", "3", "2", "1"}, // 0番目に"5"を追加
}
opts := []cmp.Option{
cmp.Transformer("NumSlice", func(in []int) []int {
out := append([]int(nil), in...)
sort.Ints(out)
return out
}),
cmp.Transformer("StringSlice", func(in []string) []string {
out := append([]string(nil), in...)
sort.Strings(out)
return out
}),
}
if diff := cmp.Diff(v1, v2, opts...); diff != "" {
t.Errorf("Compare value is mismatch (-v1 +v2):%s\n", diff)
}
}
ちゃんと比較してくれる
=== RUN TestSortSlice
sort_test.go:1774: Compare value is mismatch (-v1 +v2): &http.Compare{
NumSlice: {Id: 1, Nums: Inverse(NumSlice, []int{1, 2, 3, 4, ...})},
StringSlice: []string(Inverse(StringSlice, []string{
"1",
"2",
"3",
- "4",
+ "5",
})),
}
SortSlicesのやり方があれば教えてください。