Skip to content

Commit

Permalink
refactor: 添加对原始值是否相等的比较
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Jun 16, 2022
1 parent 5a00d8d commit def8bbc
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 6 deletions.
9 changes: 6 additions & 3 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func isNil(expr interface{}) bool {
return k >= reflect.Chan && k <= reflect.Slice && v.IsNil()
}

// 判断两个值是否相等
// 判断两个值是否相等
//
// 除了通过 reflect.DeepEqual() 判断值是否相等之外,一些类似
// 可转换的数值也能正确判断,比如以下值也将会被判断为相等:
Expand All @@ -98,9 +98,8 @@ func isEqual(v1, v2 interface{}) bool {
vv1 := reflect.ValueOf(v1)
vv2 := reflect.ValueOf(v2)

// NOTE: 这里返回 false,而不是 true
if !vv1.IsValid() || !vv2.IsValid() {
return false
return vv1.IsValid() == vv2.IsValid()
}

if vv1 == vv2 {
Expand All @@ -110,6 +109,10 @@ func isEqual(v1, v2 interface{}) bool {
vv1Type := vv1.Type()
vv2Type := vv2.Type()

if vv1Type.Comparable() && vv2Type.Comparable() && v1 == v2 {
return true
}

// 过滤掉已经在 reflect.DeepEqual() 进行处理的类型
switch vv1Type.Kind() {
case reflect.Struct, reflect.Ptr, reflect.Func, reflect.Interface:
Expand Down
20 changes: 17 additions & 3 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@ import (

func TestIsEqual(t *testing.T) {
eq := func(v1, v2 interface{}) {
t.Helper()
if !isEqual(v1, v2) {
t.Errorf("eq:[%v]!=[%v]", v1, v2)
}
}

neq := func(v1, v2 interface{}) {
t.Helper()
if isEqual(v1, v2) {
t.Errorf("eq:[%v]==[%v]", v1, v2)
}
Expand Down Expand Up @@ -50,7 +52,7 @@ func TestIsEqual(t *testing.T) {
},
)

// 比较两个元素类型可转换的map
// 比较两个元素类型可转换的 map
eq(
[]map[int]int{
{1: 1, 2: 2},
Expand All @@ -63,7 +65,7 @@ func TestIsEqual(t *testing.T) {
)
eq(map[string]int{"1": 1, "2": 2}, map[string]int8{"1": 1, "2": 2})

// 比较两个元素类型可转换的map
// 比较两个元素类型可转换的 map
eq(
map[int]string{
1: "1",
Expand All @@ -87,14 +89,26 @@ func TestIsEqual(t *testing.T) {
neq(true, "true")
neq(true, 1)
neq(true, "1")
// 判断包含不同键名的两个map
// 判断包含不同键名的两个 map
neq(map[int]int{1: 1, 2: 2}, map[int]int{5: 5, 6: 6})

// time
loc := time.FixedZone("utf+8", 8*3600)
now := time.Now()
eq(time.Time{}, time.Time{})
neq(now.In(loc), now.In(time.UTC)) // 时区不同
n1 := time.Now()
n2 := n1.Add(0)
eq(n1, n2)

// 指针
v1 := 5
v2 := 5
p1 := &v1
p2 := &v1
eq(p1, p2) // 指针相等
p2 = &v2
eq(p1, p2) // 指向内容相等
}

func TestIsEmpty(t *testing.T) {
Expand Down

0 comments on commit def8bbc

Please sign in to comment.