Go问题

Go struct能不能比较

答案:能也不能,具体情况具体分析

  1. 首先要明确的是Go中map、slice、func都不能比较

  2. 所以对于相同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)

  1. 如果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
  1. 对于不同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)
  1. 但是如果他们具备完全相同的成员(字段名、字段类型、字段个数),可以通过强制类型转换为同一类型后进行比较。
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
  1. 但是如果上述三个属性有一个不同,就无法通过编译。
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值