Go 語言程式在模組內建立類


本文將編寫一個 Go 語言程式,在模組內建立類。該程式不使用類,只使用結構體來儲存資料欄位。

模組是包含 go.mod 檔案的包的集合,該檔案位於模組的根目錄,並確定模組的目錄。

使用子結構體

在此方法中,我們將編寫一個 Go 語言程式,使用子結構體在模組內建立類。我們將建立一個名為 createstruct 的函式,該函式將從另一個模組呼叫以列印子資訊。

演算法

  • 步驟 1 − 在程式中匯入 mymodule 和 fmt 包以執行程式

  • 步驟 2 − 建立一個名為 Child 的結構體,其中包含 Name(字串型別)和 Age(整數型別)欄位

  • 步驟 3 − 建立一個名為 createstruct 的函式,並在該函式中新增列印語句

  • 步驟 4 − 然後,使用 import 語句在另一個模組中匯入此模組

  • 步驟 5 − 將孩子的姓名和年齡傳遞給 Child 結構體的建構函式

  • 步驟 6 − 從另一個模組呼叫該函式,並將該模組中的語句打印出來

  • 步驟 7 − 使用 fmt 包中的 Println 函式執行列印語句

示例

以下示例演示了使用子結構體在模組內建立類的 Go 語言程式。

package mymodule

import "fmt"
type Child struct {
   Name string
   Age  int
}

func (c *Child) createstruct() {
   fmt.Printf("Hello, my name is %s and I'm %d years old\n", c.Name, c.Age)
}
import "mymodule"  

func main() {
   c := mymodule.Child{Name: "Rahul", Age: 10}  
   c.createstruct()  
}

輸出

Hello, my name is Rahul and I’m 10 years old

使用矩形結構體

在本例中,我們將編寫一個 Go 語言程式,使用 Rectangle 結構體在模組內建立類。我們將呼叫 area 函式,該函式將返回寬度和高度的乘積。

演算法

  • 步驟 1 − 在程式中匯入 mymodule 和 fmt 包以執行程式

  • 步驟 2 − 建立一個 Rectangle 結構體,其中包含 width 和 height 欄位

  • 步驟 3 − 建立一個名為 Area 的函式,並在該函式中返回寬度和高度的乘積

  • 步驟 4 − 在另一個模組中匯入此模組,並在 main 函式中將寬度和高度傳遞給 Rectangle 結構體的建構函式

  • 步驟 5 − 呼叫 Area 函式並列印矩形的面積

  • 步驟 6 − 使用 fmt 包中的 Println 函式執行列印語句

示例

以下示例是一個使用 Rectangle 結構體在模組內建立類的 Go 語言程式

package mymodule

type Rectangle struct {
   Width  float64
   Height float64
}


func (rect Rectangle) Area() float64 {
   return rect.Width * rect.Height
}
import "mymodule"  

func main() {
   rect := mymodule.Rectangle{Width: 6, Height: 4}
   fmt.Println("The area of the rectangle is:", rect.Area())
}

輸出

The area of rectangle is 24

使用 Name 結構體

在此方法中,我們將編寫一個 Go 語言程式,使用 name 結構體在模組內建立類。將在 module1 中建立函式,並將匯入 module1 到執行 main 函式的檔案。變數用作指向結構體的指標。

演算法

  • 步驟 1 − 程式匯入 fmt 和 main 包,其中 fmt 用於格式化輸入和輸出,main 用於生成可執行程式碼

  • 步驟 2 − 建立一個名為 demo_struct 的結構體,其中包含一個名為 Name 的欄位

  • 步驟 3 − 然後,建立一個名為 Get_name 的函式,其中 demo_struct 的指標指向 s 變數

  • 步驟 4 − 在函式中,使用點表示法從 s 返回 Name

  • 步驟 5 − 在執行 main 函式的檔案中匯入該模組

  • 步驟 6 − 在 main 函式中設定結構體的欄位值

  • 步驟 7 − 使用點表示法從 s 呼叫該函式

  • 步驟 8 − 使用 fmt 包中的 Println 函式在控制檯上列印輸出

示例

以下示例是使用 name 結構體在模組內建立類的 Go 語言程式

package main

import "fmt"

type demo_struct struct {
   Name string
}

func (s *demo_struct) Get_name() string {
   return s.Name
}
package main

import "module1"

func main() {
   s := &module1.demo_struct{Name: "Ritika"}
   name := s.Get_name()
   fmt.Println(name) 
}

輸出

Ritika

結論

我們編譯並執行了使用三個示例在模組內建立類的程式。在這兩個示例中,我們在模組內建立了一個結構體並在另一個模組中匯入了該模組,但在第一個示例中,我們使用了帶子結構體的結構體,在第二個示例中,我們使用了帶矩形的結構體,在第三個示例中,我們使用結構體返回了名稱。

更新於: 2023年4月4日

158 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告