从下面代码可以看出:
1、相同实例的可以比较,但不能含有不可比较的结构体成员(切片和map),可以强转为同一结构体的也可以比较
2、struct不能作为map的key
package main
import (
"fmt"
"reflect"
)
type Comp1 struct {
Age int
Name string
}
type Comp2 struct {
Age int
Name string
Ms []int // (struct containing []int cannot be compared)
Ks map[string]string
}
type Comp3 struct {
Age int
Name string
Ms [2]bool //[]boolb不可以比较,[2]bool可以比较(切片和map不能比较)
}
type Comp4 struct {
Age int
Name string
Ms [2]bool
}
func main() {
t1 := Comp1{Age: 20, Name: "wangwang"}
t2 := Comp1{Age: 27, Name: "mht"}
fmt.Println("same ?", reflect.DeepEqual(t1, t2))
fmt.Println("same ?", t1 == t2)
fmt.Println("same ?", &t1 == &t2)
t3 := Comp2{Age: 20, Name: "wangwang"}
t4 := Comp2{Age: 27, Name: "mht"}
fmt.Println("same ?", reflect.DeepEqual(t3, t4))
t3 = Comp2{Age: 20, Name: "wangwang"}
t4 = Comp2{Age: 20, Name: "wangwang"}
t5 := t3
fmt.Println("same ?", reflect.DeepEqual(t3, t4))
//fmt.Println("same ?", t3 == t4 )
fmt.Println("same ?", &t3 == &t4)
fmt.Println("same ?", reflect.DeepEqual(t3, t5))
fmt.Println("same ?", &t3 == &t5)
//fmt.Println("same ?", t3 == t1 )//(mismatched types Comp2 and Comp1)
t6 := Comp3{Age: 20, Name: "wangwang"}
t7 := Comp4{Age: 20, Name: "wangwang"}
//fmt.Println("same ?", t7 == t6)//(mismatched types Comp4 and Comp3)
fmt.Println("same ?", t7 == Comp4(t6))
fmt.Println("same ?", reflect.DeepEqual(t6, t7))
//m := make(map[Comp4]int)//type Comp4 is not an expression
//m[Comp4]++
//fmt.Println(m[t7])
}
网友评论