Golang中的通用方法参数

时间:2015-02-08 10:59:43

标签: generics go struct interface

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

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

我尝试过使用接口,但这对我的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)
}

我明白了

  

错误prog.go:39:不能使用人类(类型[]人类)作为类型[]哺乳动物参数计数

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

2 个答案:

答案 0 :(得分:6)

你无法在Go中完全按照你的要求行事。在Go中做最近事的方法就像这样,如下面的代码所示:

type Ids interface{
  Id() int
}

func (this Mammal) Id() int{
  return this.ID
} 

func (this Human) Id() int{
  return this.ID
} 


func Count(ms []Ids) *[]string {
...
    IDs[i] = strconv.Itoa(int(m.Id()))
...
}

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

  humans := []Ids{
    Human{ID:1, Name: "Peter", HairColor: "Black"},
    Human{ID:2, Name: "Paul", HairColor: "Red"},
  }
  ...
}  

这是工作example

答案 1 :(得分:4)

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

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

type Human interface {
    Mammal

    GetHairColor() string
}

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

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()

制作你的哺乳动物和人类片段:

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上的完整工作代码。