Golang 结构体平等性
Golang中的结构是一种用户定义的类型,它允许我们将不同类型的元素组合成一个单元。任何现实世界中的实体,只要有一些属性或字段,都可以用结构来表示。这个概念通常与面向对象编程中的类相比。它可以被称为轻量级的类,不支持继承,但支持组合。
在Go语言中,如果两个结构的类型相同,并且包含相同的字段值,你可以在 ==运算符 或 DeeplyEqual()方法 的帮助下进行比较 。 如果两个结构的字段值相同,操作符和方法都会返回true,否则会返回false。而且,如果比较的变量属于不同的结构,那么编译器将给出一个错误。让我们借助例子来讨论这个概念:
注意: DeeplyEqual()方法是在 “reflect “包中定义的。
例1:
// Go program to illustrate the
// concept of struct equality
// using == operator
package main
import "fmt"
// Creating a structure
type Author struct {
name string
branch string
language string
Particles int
}
// Main function
func main() {
// Creating variables
// of Author structure
a1 := Author{
name: "Moana",
branch: "CSE",
language: "Python",
Particles: 38,
}
a2 := Author{
name: "Moana",
branch: "CSE",
language: "Python",
Particles: 38,
}
a3 := Author{
name: "Dona",
branch: "CSE",
language: "Python",
Particles: 38,
}
// Checking if a1 is equal
// to a2 or not
// Using == operator
if a1 == a2 {
fmt.Println("Variable a1 is equal to variable a2")
} else {
fmt.Println("Variable a1 is not equal to variable a2")
}
// Checking if a1 is equal
// to a2 or not
// Using == operator
if a2 == a3 {
fmt.Println("Variable a2 is equal to variable a3")
} else {
fmt.Println("Variable a2 is not equal to variable a3")
}
}
输出:
Variable a1 is equal to variable a2
Variable a2 is not equal to variable a3
例2:
// Go program to illustrate the
// concept of struct equality
// using DeepEqual() method
package main
import (
"fmt"
"reflect"
)
// Creating a structure
type Author struct {
name string
branch string
language string
Particles int
}
// Main function
func main() {
// Creating variables
// of Author structure
a1 := Author{
name: "Soana",
branch: "CSE",
language: "Perl",
Particles: 48,
}
a2 := Author{
name: "Soana",
branch: "CSE",
language: "Perl",
Particles: 48,
}
a3 := Author{
name: "Dia",
branch: "CSE",
language: "Perl",
Particles: 48,
}
// Comparing a1 with a2
// Using DeepEqual() method
fmt.Println("Is a1 equal to a2: ", reflect.DeepEqual(a1, a2))
// Comparing a2 with a3
// Using DeepEqual() method
fmt.Println("Is a2 equal to a3: ", reflect.DeepEqual(a2, a3))
}
输出:
Is a1 equal to a2: true
Is a2 equal to a3: false