golang 相同结构体比较方式比较
golang 相同结构体比较方式比较
使用==
示例:
type Student struct {
Name string
Age int
}
type Class struct {
Name string
}
func main() {
s1 := Student{
Name: "ysm",
Age: 23,
}
s2 := Student{
Name: "ysm",
Age: 23,
}
if s1 == s2 {
log.Println("这两个值相同")
} else {
log.Println("这两个值不相同")
}
}
# 输出:这两个值相同
缺点:如果结构体中有指针类型,就不能够进行比较。因为对于指针类型的比较是比较地址,不是比较指针指向的内容
示例:
type Student struct {
Name string
Age int
C *Class
}
type Class struct {
Name string
}
func main() {
s1 := Student{
Name: "ysm",
Age: 23,
C: &Class{
Name: "3班",
},
}
s2 := Student{
Name: "ysm",
Age: 23,
C: &Class{
Name: "3班",
},
}
if s1 == s2 {
log.Println("这两个值相同")
} else {
log.Println("这两个值不相同")
}
}
# 输出:这两个值不相同
使用reflect.DeepEqual
示例:
type Student struct {
Name string
Age int
C *Class
}
type Class struct {
Name string
}
func main() {
s1 := Student{
Name: "ysm",
Age: 23,
C: &Class{
Name: "3班",
},
}
s2 := Student{
Name: "ysm",
Age: 23,
C: &Class{
Name: "3班",
},
}
if reflect.DeepEqual(s1, s2) {
log.Println("这两个值相同")
} else {
log.Println("这两个值不相同")
}
}
# 输出:这两个值相同
原因:使用reflect.DeepEqual是进行值比较
缺点:运行时间慢