Golang 如何比较struct、slice和map的相等性
==intboolstructslicemap
比较struct的相等性
struct
type person struct {
name string
age int
}
func (p person) Equals(other person) bool {
return p.name == other.name && p.age == other.age
}
p1 := person{name: "Alice", age: 20}
p2 := person{name: "Bob", age: 30}
if p1.Equals(p2) {
fmt.Println("Equal")
} else {
fmt.Println("Not equal")
}
Equalsperson
structreflectreflect
import "reflect"
func structEquals(a, b interface{}) bool {
valueA := reflect.ValueOf(a)
valueB := reflect.ValueOf(b)
// 如果类型不同,则返回false
if valueA.Type() != valueB.Type() {
return false
}
// 遍历结构体的每个字段
for i := 0; i < valueA.NumField(); i++ {
fieldA := valueA.Field(i)
fieldB := valueB.Field(i)
// 如果字段类型不同,则返回false
if fieldA.Type() != fieldB.Type() {
return false
}
// 如果字段值不同,则返回false
if !reflect.DeepEqual(fieldA.Interface(), fieldB.Interface()) {
return false
}
}
return true
}
type person struct {
name string
age int
}
p1 := person{name: "Alice", age: 20}
p2 := person{name: "Bob", age: 30}
if structEquals(p1, p2) {
fmt.Println("Equal")
} else {
fmt.Println("Not equal")
}
reflectValueOfNumField
reflect
比较slice的相等性
slicereflect.DeepEqual
a := []int{1, 2, 3}
b := []int{1, 2, 3}
if reflect.DeepEqual(a, b) {
fmt.Println("Equal")
} else {
fmt.Println("Not equal")
}
reflect.DeepEqualsliceslice
slicestructslicemapstructslice
type person struct {
name string
age int
}
a := []person{{name: "Alice", age: 20}, {name: "Bob", age: 30}}
b := []person{{name: "Alice", age: 20}, {name: "Charlie", age: 40}}
equal := true
for i := 0; i < len(a); i++ {
if !a[i].Equals(b[i]) {
equal = false
break
}
}
if equal {
fmt.Println("Equal")
} else {
fmt.Println("Not equal")
}
sliceEquals