Golang 如何比较具有指针字段的两个结构实例
在golang中,指针是用来存储其他变量地址的变量。结构体是面向对象编程中类的对应物,可以在结构体中放置不同的字段,这些字段可以后续实现,并且具有int、float、string等类型。在本文中,我们将编写一段Go语言程序来比较具有指针字段的两个结构实例。
将变量“b”的地址赋值给变量“a”的数学表示方法为-
a = &b
&表示地址运算符,并接收变量b的内存地址,并将其赋值给变量a。
步骤
- 步骤 1 - 此程序根据需要导入main和fmt包。
-
步骤 2 - 创建一个包含两个字段的Employee结构体,其中Name的类型为string,Age的类型为int。
-
步骤 3 - 创建一个main函数。
-
步骤 4 - 在main函数中,创建一个e1变量,并使用地址运算符初始化它的值。
-
步骤 5 - 在此步骤中,创建一个e2变量,并使用地址运算符初始化其字段的值。
-
步骤 6 - 然后,将e3赋值为e1。
-
步骤 7 - 在此步骤中,检查e1和e2的相等性,并在第二种情况下检查e1和e3的相等性。
-
步骤 8 - 将返回一个布尔值,该值将使用来自fmt包的Println函数在控制台上打印出来,其中ln表示新行。
示例1
在此示例中,我们将编写一个Go语言程序,使用一个包含两个字段Name和Age的Employee结构体来比较两个结构体实例。
package main
import "fmt"
type Employee struct {
Name string
Age int
}
func main() {
e1 := &Employee{Name: "Karan", Age: 28}
e2 := &Employee{Name: "Robin", Age: 35}
e3 := e1
fmt.Println("Is e1 is equal to e2?")
fmt.Println(e1 == e2)
fmt.Println("Is e1 equal to e3?")
fmt.Println(e1 == e3)
}
输出
Is e1 is equal to e2?
false
Is e1 equal to e3?
true
示例2
在这个示例中,我们将编写一个Go语言程序,使用一个包含两个字段Model和Year的Car结构体来比较两个结构体实例。
package main
import "fmt"
type Car struct {
Model string
Year int
}
func main() {
c1 := &Car{Model: "Suzuki", Year: 2022}
c2 := &Car{Model: "Hyundai", Year: 2019}
c3 := c2
fmt.Println("is c1 equal to c2?")
fmt.Println(c1 == c2)
fmt.Println("is derefrenced c2 is equal to c3?")
fmt.Println(*c2 == *c3)
fmt.Println("Is the model and year of c1 and c2 same?")
fmt.Println(c1.Model == c2.Model && c1.Year == c2.Year)
fmt.Println("Is c1 equal to c3?")
fmt.Println(c1 == c3)
}
输出
is c1 equal to c2?
false
is derefrenced c2 is equal to c3?
true
Is the model and year of c1 and c2 same?
false
Is c1 equal to c3?
false
结论
在本文中,我们通过两个示例探讨了比较具有指针字段的两个结构体的程序。在第一个示例中,我们使用了一个Employee结构体,在第二个示例中,我们使用了一个Car结构体。
极客笔记