Skip to content

Commit bf23379

Browse files
committed
feat: allow to compare n-dimensions slice/array.
1 parent 6e90edf commit bf23379

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

compare_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,12 @@ func TestIsEqual(t *testing.T) {
285285
assert.Equal(isEqual(slice1, slice4), false)
286286
assert.Equal(isEqual(slice1, slice5), false)
287287

288+
assert.True(isEqual([][]any{{1}, {2, 3}}, [][]any{{1}, {2, 3}}))
289+
assert.NotTrue(isEqual([][]any{{1}, {2, 3}}, [][]any{{1.0}, {2.0, 3.0}}))
290+
assert.NotTrue(isEqual([][]any{{1}, {2, 3}}, [][]any{{"1"}, {"2", "3"}}))
291+
assert.True(isEqual([][][]any{{{1}, {2}}, {{2, 3}}}, [][][]any{{{1}, {2}}, {{2, 3}}}))
292+
assert.NotTrue(isEqual([][][]any{{{1}, {2}}, {{2, 3}}}, [][][]any{{{1}, {2}}, {{2, "3"}}}))
293+
288294
assert.Equal(isEqual(testStruct1{A: 0}, testStruct1{A: 0}), true)
289295
assert.Equal(isEqual(testStruct1{A: 0}, testStruct1{A: 1}), false)
290296
assert.Equal(isEqual(s1, s1), true)

slice.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,17 @@ func isSliceEqual(v1, v2 reflect.Value) bool {
135135
}
136136

137137
for i := 0; i < v1.Len(); i++ {
138-
if v1.Index(i).Interface() != v2.Index(i).Interface() {
139-
return false
138+
v1v := v1.Index(i).Interface()
139+
v2v := v2.Index(i).Interface()
140+
141+
if v1.Index(i).Comparable() && v2.Index(i).Comparable() && v1.Type().ConvertibleTo(v2.Type()) {
142+
if v1v != v2v {
143+
return false
144+
}
145+
} else {
146+
if ok := isEqual(v1v, v2v); !ok {
147+
return false
148+
}
140149
}
141150
}
142151

0 commit comments

Comments
 (0)