📜  Golang 中的结构相等

📅  最后修改于: 2021-10-24 14:24:57             🧑  作者: Mango

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,
    }
      
    // Compairing a1 with a2
    // Using DeepEqual() method
    fmt.Println("Is a1 equal to a2: ", reflect.DeepEqual(a1, a2))
  
    // Compairing 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