📜  如何比较结构与分配给 Golang 中数据字段的不同值?

📅  最后修改于: 2021-10-25 02:34:58             🧑  作者: Mango

结构(Structure)是 Golang 中用户定义的类型,它包含一组命名字段/属性,这些字段/属性通过组合一个或多个类型来创建自己的数据类型。此外,这个概念通常与面向对象编程中的类进行比较。结构体具有相同或不同数据类型的不同字段,并通过组合一组固定的唯一字段来声明。

定义结构类型:结构的声明以关键字类型开始,然后定义新结构的名称,然后是关键字结构。在大括号之后开始定义一系列具有名称和类型的数据字段。

句法:

type StructName struct {
    field1 fieldType1
    field2 fieldType2
}

例子:

// Creating a structure
type Employee struct {
    firstName string
        lastName string
            salary int
                age int
}

下面给出实施例以explain-使用运算符,相同类型的结构进行比较。

示例 1:

// Go program to illustrate the
// concept of Struct comparison
// using == operator
package main
  
import "fmt"
  
// Creating a structure
type Employee struct {
    FirstName, LastName string
    Salary              int
    Age                 int
}
  
// Main function
func main() {
  
    // Creating variables
    // of Employee structure
    A1 := Employee{
        FirstName: "Seema",
        LastName:  "Singh",
        Salary:    20000,
        Age:       23,
    }
  
    A2 := Employee{
        FirstName: "Seema",
        LastName:  "Singh",
        Salary:    20000,
        Age:       23,
    }
  
    // 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")
    }
}

输出:

Variable A1 is equal to variable A2

示例 2:

// Go program to illustrate the
// concept of Struct comparison
// with the Different Values Assigned
package main
  
import "fmt"
  
// Creating a structure
type triangle struct {
    side1 float64
    side2 float64
    side3 float64
    color string
}
  
// Main function
func main() {
  
    // Creating variables
    // of Triangle structure
    var tri1 = triangle{10, 20, 30, "Green"}
    tri2 := triangle{side1: 20, side2: 10,
                  side3: 10, color: "Red"}
  
    // Checking if tri1 is equal
    // to tri2 or not
    // Using == operator
    if tri1 == tri2 {
        fmt.Println("True")
    } else {
        fmt.Println("False")
    }
  
    // Checking if tri3 is equal
    // to tri4 or not
    // Using == operator
    tri3 := new(triangle)
    var tri4 = &triangle{}
  
    if tri3 == tri4 {
        fmt.Println("True")
    } else {
        fmt.Println("False")
    }
}

输出:

False
False