如何在 Golang 中宣告介面?


在 Go 語言中宣告介面意味著建立一個新的命名型別,該型別定義了一組方法簽名。在 Go 語言中,我們可以使用單方法介面、多方法介面以及嵌入式介面來宣告介面。在本文中,我們將瞭解這些方法,並藉助各種示例在 Go 語言中宣告介面。

方法 1:單方法介面

第一種方法涉及單個介面,在這種方法中,我們描述所有實現型別必須滿足的介面。

演算法

  • 建立一個名為 CreateSound() 的單方法介面。

  • 現在,建立表示貓的結構體 cat。

  • 在 cat 結構體上實現 CreateSound() 函式。它將列印 "meow!" 到控制檯。

  • 現在在 main 函式中宣告一個型別為 Animal 的變數。

  • 在 animal 變數上,使用 CreateSound() 函式。

  • 它輸出 "meow!" 到控制檯。

示例

此程式碼定義了一個介面 Animal 和一個結構體 Cat。該介面定義了一個名為“Create Sound()”的單方法,該方法列印輸出,並且 Cat 結構體實現了 CreateSound() 函式。

package main

import "fmt"

type Animal interface {
   CreateSound()
}

type cat struct{}

func (d cat) CreateSound() {
   fmt.Println("meow!")
}

func main() {
   var animal Animal
   animal = cat{}
   animal.CreateSound() // Output: Woof!
}

輸出

meow!

方法 2:使用多方法介面

此方法涉及使用多個介面,在這種方法中,我們將看到 Go 語言介面可以包含多個方法。

演算法

  • 使用兩個方法 Area() 和 Perimeter 定義 Shape 介面。

  • 現在,建立一個名為 Rectangle 的結構體,型別為 float64 的 length 和 width。

  • 實現 Area() 函式。返回 length 乘以 width 的結果。

  • 實現 Perimeter() 函式。返回使用公式計算的周長 = 2 * (length + width)。

  • 將型別為 Rectangle 的值分配給 shape 變數,並將 length 設定為 8,width 設定為 5。

  • 列印 Area() 函式的結果。列印 Perimeter() 函式的結果。

示例

以下示例演示了在 Go 語言中使用介面來計算矩形的面積和周長。

package main

import "fmt"

type Shape interface {
   Area() float64
   Perimeter() float64
}

type Rectangle struct {
   length, width float64
}

func (r Rectangle) Area() float64 {
   return r.length * r.width
}

func (r Rectangle) Perimeter() float64 {
   return 2 * (r.length + r.width)
}

func main() {
   var shape Shape
   shape = Rectangle{length: 8, width: 5}
   fmt.Println(shape.Area())
   fmt.Println(shape.Perimeter())
}

輸出

40
26

方法 3:使用嵌入式介面

此方法涉及將一個介面嵌入到另一個介面中,允許新介面採用嵌入式介面的所有方法。

演算法

  • 建立一個名為 Reader 的介面,它具有一個返回 []byte 的 Read() 函式。

  • 建立名為 Writer 的介面並定義函式 Write(data []byte)。

  • 定義一個結構體 file。

  • 實現 File 結構體的 Read() 函式。

  • 實現 File 結構體的 Write(data []byte) 函式。

  • 在 main 函式中,宣告一個型別為 ReadWrite 的變數 rw。

  • 將 rw 變數賦值為 File 型別,表示 File 實現了 ReadWrite 介面。

  • 在 rw 變數上執行 Read() 方法並儲存結果。

  • 將 data 變數作為引數傳遞給 rw 變數上的 Write(data) 方法。

  • 程式使用 Read() 函式從檔案中讀取資料,並使用 send() 方法將資料傳送到控制檯。

示例

以下示例解釋了介面組合的概念,它涉及將多個介面混合在一起以建立一個新的介面。

package main

import "fmt"

type Reader interface {
   Read() []byte
}

type Writer interface {
   Write(data []byte)
}

type ReadWrite interface {
   Reader
   Writer
}

type File struct {
   // implementation details
}

func (f File) Read() []byte {
   return []byte("Read data from file")
}

func (f File) Write(data []byte) {
   fmt.Println("Write data to file:", string(data))
}

func main() {
   var rw ReadWrite
   rw = File{}
   data := rw.Read()
   rw.Write(data)
}

輸出

Write data to file: Read data from file

結論

在本文中,我們討論瞭如何使用單介面、多介面和嵌入式介面方法來宣告介面。Go 語言中的介面是實現程式碼多型性和使程式碼靈活的非常有用的工具。

更新於: 2023-07-05

143 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.