以下代码中有三种结构体比较,能否编译通过呢
package main
import "fmt"
func main() {
sn1 := struct {
age int
name string
}{age: 11, name: "qq"}
sn2 := struct {
age int
name string
}{age: 11, name: "qq"}
if sn1 == sn2 {
fmt.Println("sn1 == sn2")
}
sq1 := struct {
age int
name string
}{age: 11, name: "qq"}
sq2 := struct {
name string
age int
}{age: 11, name: "qq"}
if sq1 == sq2 {
fmt.Println("sq1 == sq2")
}
sm1 := struct {
age int
m map[string]string
}{age: 11, m: map[string]string{"a": "1"}}
sm2 := struct {
age int
m map[string]string
}{age: 11, m: map[string]string{"a": "1"}}
if sm1 == sm2 {
fmt.Println("sm1 == sm2")
}
}
编译结果如下:
./main.go:34:9: invalid operation: sq1 == sq2 (mismatched types struct { age int; name string } and struct { name string; age int })
./main.go:48:9: invalid operation: sm1 == sm2 (struct containing map[string]string cannot be compared)
golang中结构体的比较有以下规则:
- 只有相同类型的结构体才可以比较
- 结构体必须字段属性和顺序都相同,才是相同结构体
- 结构体中有不可比较类型,如map,slice,则结构体不能用==比较
可以使用reflect.DeepEqual进行比较
if reflect.DeepEqual(sm1, sm2) {
fmt.Println("sm1 == sm2")
} else {
fmt.Println("sm1 != sm2")
}