Go 比较结构体,对结构体进行比较,要先看它们的类型和值是否相同。对于类型相同的结构体,可使用相等性运算符来比较。要判断两个结构体是否相等,可使用==;要判断它们是否不等,可使用!=
。在如下程序中,创建了两个数据字段值相等的结构体,由于它们相等,因此比较运算符==返回true。
package main
import (
"fmt"
)
type Drink struct {
Name string
Ice bool
}
func main() {
a := Drink{
Name: "coolcou",
Ice: true,
}
b := Drink{
Name: "coolcou",
Ice: true,
}
if a == b {
fmt.Println("a and b are the same")
}
fmt.Printf("%+v\n", a)
fmt.Printf("%+v\n", b)
}
运行结果如下:
不能对两个类型不同的结构体进行比较,否则将导致编译错误。因此,试图比较两个结构体之前,必须确定它们的类型相同。要检查结构体的类型,可使用Go语言包reflect。在如下程序中,使用了reflect包来检查结构体的类型。
package main
import (
"fmt"
"reflect"
)
type Drink struct {
Name string
Ice bool
}
func main() {
a := Drink{
Name: "coolcou",
Ice: true,
}
b := Drink{
Name: "coolcou",
Ice: true,
}
fmt.Println(reflect.TypeOf(a))
fmt.Println(reflect.TypeOf(b))
}
运行结果如下:
酷客教程相关文章:
评论前必须登录!
注册