方法
DeepEqual方法
官方的reflect
包中有个DeepEqual
方法,可以用来判断任意x和y是否相等。相同类型的两个值可能相等,不同类型的值永远不会相等。
func DeepEqual(x, y interface{}) bool {
if x == nil || y == nil {
return x == y
}
v1 := ValueOf(x)
v2 := ValueOf(y)
if v1.Type() != v2.Type() {
return false
}
return deepValueEqual(v1, v2, make(map[visit]bool), 0)
}
首先DeepEqual
会判断其类型是否相同,接着才会根据类型进行层层判断。
func ReflectSlice(a, b []string) bool {
return reflect.DeepEqual(a, b)
}
循环判断切片中的值
func CompareSlice(a, b []string) bool {
if len(a) != len(b) {
return false
}
if (a == nil) != (b == nil) {
return false
}
for key, value := range a {
if value != b[key] {
return false
}
}
return true
}
测试
package main
import "testing"
type testSlice struct {
ins1 []string
ins2 []string
out bool
}
var tests = []testSlice{
{ins1: []string{"a", "b", "c",}, ins2: []string{"a", "b", "c",}, out: true,},
{ins1: []string{"a", "b", "c",}, ins2: []string{"a", "b", "c", "d"}, out: false,},
{ins1: []string{"a", "b", "c",}, ins2: []string{"a", "b", "d"}, out: false,},
}
func BenchmarkReflectSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, value := range tests {
if value.out != ReflectSlice(value.ins1, value.ins2) {
b.Error("test failed")
}
}
}
}
func BenchmarkCompareSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, value := range tests {
if value.out != CompareSlice(value.ins1, value.ins2) {
b.Error("test failed")
}
}
}
}
经过测试,使用循环去比较每个值的方法比使用官方提供的DeepEqual
方法快一些。可能DeepEqual
方法试用的情况比较多,做了一些类型判断等造成相对较慢。
goos: windows
goarch: amd64
BenchmarkReflectSlice-12 2000000 907 ns/op
BenchmarkCompareSlice-12 50000000 31.2 ns/op
PASS
ok command-line-arguments 4.459s