Go struct能不能比较
答案:能也不能,具体情况具体分析
-
首先要明确的是Go中map、slice、func都不能比较
-
所以对于相同struct的不同实例,如果struct中有map、slice、func的话无法比较,无法编译。
type t1 struct {
m int
n int
s []int
}
type t2 struct {
m int
n int
}
func main() {
x := t1{m: 0, n: 0}
y := t1{m: 0, n: 1}
fmt.Print(x == y)
}
//报错:invalid operation: x == y (struct containing []int cannot be compared)
- 如果struct中没有不可比较的类型,那么相同struct的不同实例间可以比较,依次比较struct中的成员变量。
type t1 struct {
m int
n int
}
type t2 struct {
m int
n int
}
func main() {
x := t1{m:0,n: 0}
y := t1{m:0,n: 1}
fmt.Print(x == y)
}
//输出:false
- 对于不同struct,如果直接比较的话会无法通过编译。
type t1 struct {
m int
n int
}
type t2 struct {
m int
n int
}
func main() {
x := t1{m:0,n: 0}
y := t2{m:0,n: 1}
fmt.Print(x == y)
}
//报错:invalid operation: x == y (mismatched types t1 and t2)
- 但是如果他们具备完全相同的成员(字段名、字段类型、字段个数),可以通过强制类型转换为同一类型后进行比较。
type t1 struct {
m int
n int
}
type t2 struct {
m int
n int
}
func main() {
x := t1{m: 0, n: 0}
y := t2{m: 0, n: 1}
fmt.Print(x == t1(y))
}
//输出:false
- 但是如果上述三个属性有一个不同,就无法通过编译。
type t1 struct {
m int
n int
}
type t2 struct {
m int
n2 int
}
func main() {
x := t1{m: 0, n: 0}
y := t2{m: 0, n2: 1}
fmt.Print(x == t1(y))
}
//报错:cannot convert y (type t2) to type t1