Skip to content
鼓励作者:欢迎打赏犒劳

go对象比较

基本类型:可以直接使用 ==

go
a := 10
b := 10
fmt.Println(a == b) // true

s1 := "hello"
s2 := "hello" 
fmt.Println(s1 == s2) // true

结构体:需要根据字段类型决定

可比较的结构体

go
type Person struct {
    Name string
    Age  int
}

p1 := Person{"Alice", 20}
p2 := Person{"Alice", 20}
fmt.Println(p1 == p2) // true - 因为所有字段都是可比较类型

包含不可比较字段的结构体

go
type Container struct {
    Data []int      // 切片不可比较
    // Info map[string]int // map也不可比较
}

c1 := Container{Data: []int{1, 2, 3}}
c2 := Container{Data: []int{1, 2, 3}}
// fmt.Println(c1 == c2) // 编译错误:包含不可比较字段

引用类型:特殊规则

切片 - 不能直接 ==

go
s1 := []int{1, 2, 3}
s2 := []int{1, 2, 3}
// fmt.Println(s1 == s2) // 编译错误

// 需要使用 reflect.DeepEqual
fmt.Println(reflect.DeepEqual(s1, s2)) // true

Map - 不能直接 ==

go
m1 := map[string]int{"a": 1}
m2 := map[string]int{"a": 1}
// fmt.Println(m1 == m2) // 编译错误

fmt.Println(reflect.DeepEqual(m1, m2)) // true

最佳实践对象还是用DeepEqual

go
import "reflect"

type ComplexStruct struct {
    Name    string
    Scores  []int
    Info    map[string]interface{}
}

a := ComplexStruct{
    Name:   "test",
    Scores: []int{1, 2, 3},
    Info:   map[string]interface{}{"x": 1},
}

b := ComplexStruct{
    Name:   "test",
    Scores: []int{1, 2, 3},
    Info:   map[string]interface{}{"x": 1},
}

fmt.Println(reflect.DeepEqual(a, b)) // true

自定义比较函数

go
func (p Person) Equals(other Person) bool {
    return p.Name == other.Name && p.Age == other.Age
}

func (c Container) Equals(other Container) bool {
    if len(c.Data) != len(other.Data) {
        return false
    }
    for i, v := range c.Data {
        if v != other.Data[i] {
            return false
        }
    }
    return true
}

Time类型比较

go
t1 := time.Now()
t2 := t1.Add(time.Hour)

// 直接使用 == 比较
fmt.Println(t1 == t2) // false - 不同时间

// 使用专门的方法更清晰
fmt.Println(t1.Equal(t2))   // 是否相等
fmt.Println(t1.Before(t2))  // t1 是否在 t2 之前
fmt.Println(t1.After(t2))   // t1 是否在 t2 之后

// 计算时间差
diff := t2.Sub(t1)
fmt.Println(diff) // 1h0m0s

指针比较

在 Go 中,指针可以使用 == 进行比较,但有一些重要的规则和注意事项。

  • 指针比较的是内存地址,不是指向的内容
  • 即使两个指针指向的内容完全相同,如果地址不同,== 也会返回 false

指针与指针的比较

go
type Person struct {
    Name string
    Age  int
}

p1 := Person{"Alice", 20}
p2 := Person{"Alice", 20}
ptr1 := &p1
ptr2 := &p1
ptr3 := &p2

fmt.Println(ptr1 == ptr2) // true - 指向同一个对象
fmt.Println(ptr1 == ptr3) // false - 指向不同对象(即使对象内容相同)

指针与 nil 的比较

go
var ptr *Person
fmt.Println(ptr == nil) // true

ptr = &Person{}
fmt.Println(ptr == nil) // false

如有转载或 CV 的请标注本站原文地址