go - Golang 中的泛型方法参数

标签 go methods struct interface

我需要帮助才能使这项工作适用于任何类型。

我有一个函数,我需要接受具有 ID 属性的其他类型。

我尝试过使用接口(interface),但这对我的 ID 属性案例不起作用。这是代码:

package main


import (
  "fmt"
  "strconv"
  )

type Mammal struct{
  ID int
  Name string 
}

type Human struct {  
  ID int
  Name string 
  HairColor string
}

func Count(ms []Mammal) *[]string { // How can i get this function to accept any type not just []Mammal
   IDs := make([]string, len(ms))
   for i, m := range ms {
     IDs[i] = strconv.Itoa(int(m.ID))
   }
   return &IDs
}

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

  humans := []Human{
    Human{ID:1, Name: "Peter", HairColor: "Black"},
    Human{ID:2, Name: "Paul", HairColor: "Red"},
  } 
  numberOfMammalIDs := Count(mammals)
  numberOfHumanIDs := Count(humans)
  fmt.Println(numberOfMammalIDs)
  fmt.Println(numberOfHumanIDs)
}

我明白了

error prog.go:39: cannot use humans (type []Human) as type []Mammal in argument to Count

有关更多详细信息,请参阅 Go Playground http://play.golang.org/p/xzWgjkzcmH

最佳答案

使用接口(interface)而不是具体类型,并使用embedded interfaces因此不必在两种类型中都列出常用方法:

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

type Human interface {
    Mammal

    GetHairColor() string
}

下面是基于您使用 embedded types 的代码实现的这些接口(interface)。 (结构):

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
}

当然,在您的 Count() 函数中,您只能引用方法,而不能引用实现的字段:

IDs[i] = strconv.Itoa(m.GetID())  // Access ID via the method: GetID()

并创建您的哺乳动物和人类 slice :

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"},
}

这是 Go Playground 上的完整工作代码.

关于go - Golang 中的泛型方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393166/

相关文章:

java - 我正在尝试用 Java 将与投注相关的组件添加到我的游戏中,但程序在要求投注金额后停止工作

c++结构包含对象

c++ - 将变量分配给字符串

html - html.EscapeString() 和 template.HTMLEscapeString() 有什么区别?

JAVA:不是一个声明 - 用于调用 'long' ?

java - 从父类方法调用子类方法

c - 使用 C 结构成员的连续内存

xml - 在 Go 中将通用 csv 转换为 xml

algorithm - 我应该在代码中更改什么以生成从 0 1 1 开始的斐波那契数列

unicode - 如何在 Go 中将 unicode 字符串从数据库转换为 utf 字符串?