如何在Go語言中比較兩個包含指標欄位的結構體例項?


在Go語言中,指標是儲存其他變數地址的變數。結構體是面向物件程式設計中類的對應物,可以將不同的欄位放在結構體中,這些欄位可以在以後實現,並且它們具有int、float、string等型別。在本文中,我們將編寫一個Go語言程式來比較兩個包含指標作為欄位的結構體例項。

將變數“b”的地址賦給變數“a”的數學表示:

a = &b 

& 表示地址運算子,它接收變數b的記憶體地址並將其賦值給變數a。

演算法

  • 步驟1 − 此程式匯入main和fmt作為必要的包

  • 步驟2 − 建立一個Employee結構體,其中包含兩個欄位:Name(字串型別)和age(整數型別)

  • 步驟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結構體。

更新於:2023年7月6日

873 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告