首頁  >  文章  >  後端開發  >  如何使用通用方法參數和介面來處理 Golang 中的哺乳動物和人類物件切片?

如何使用通用方法參數和介面來處理 Golang 中的哺乳動物和人類物件切片?

Barbara Streisand
Barbara Streisand原創
2024-10-28 17:36:02581瀏覽

How can I use generic method parameters and interfaces to process both slices of Mammal and Human objects in Golang?

Golang 中的泛型方法參數

在 Golang 中,為了使函數能夠接受任何類型,可以使用泛型方法參數。當方法需要具有特定屬性的類型時,可以使用介面。下面是一個函數需要接受具有 ID 屬性的類型的範例。

<code class="go">type MammalImpl struct {
    ID   int
    Name string
}

func (m MammalImpl) GetID() int {
    return m.ID
}

func (m MammalImpl) GetName() string {
    return m.Name
}

type HumanImpl struct {
    MammalImpl
    HairColor string
}

func (h HumanImpl) GetHairColor() string {
    return h.HairColor
}</code>

在此程式碼中,已定義介面及其嵌入式實作 Mammal人類。這確保了這兩種類型都可以在 Count 函數中使用,該函數現在透過 GetID 方法間接存取 ID 屬性。

<code class="go">func Count(ms []Mammal) *[]string {
   IDs := make([]string, len(ms))
   for i, m := range ms {
     IDs[i] = strconv.Itoa(m.GetID())
   }
   return &IDs
}</code>

透過使用通用方法參數和接口,該函數現在可以處理 MammalHuman 物件的切片。

以下是完整的工作代碼:

<code class="go">import (
    "fmt"
    "strconv"
)

type Mammal interface {
    GetID() int
    GetName() string
}

type Human interface {
    Mammal

    GetHairColor() string
}

type MammalImpl struct {
    ID   int
    Name string
}

func (m MammalImpl) GetID() int {
    return m.ID
}

func (m MammalImpl) GetName() string {
    return m.Name
}

type HumanImpl struct {
    MammalImpl
    HairColor string
}

func (h HumanImpl) GetHairColor() string {
    return h.HairColor
}

func Count(ms []Mammal) *[]string {
    IDs := make([]string, len(ms))
    for i, m := range ms {
        IDs[i] = strconv.Itoa(m.GetID())
    }
    return &IDs
}

func main() {
    mammals := []Mammal{
        MammalImpl{1, "Carnivorious"},
        MammalImpl{2, "Ominivorious"},
    }

    humans := []Mammal{
        HumanImpl{MammalImpl: MammalImpl{ID: 1, Name: "Peter"}, HairColor: "Black"},
        HumanImpl{MammalImpl: MammalImpl{ID: 2, Name: "Paul"}, HairColor: "Red"},
    }

    numberOfMammalIDs := Count(mammals)
    numberOfHumanIDs := Count(humans)
    fmt.Println(numberOfMammalIDs)
    fmt.Println(numberOfHumanIDs)
}</code>

以上是如何使用通用方法參數和介面來處理 Golang 中的哺乳動物和人類物件切片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn