Golang中的通用方法参数 [英] Generic Method Parameters in Golang
问题描述
我需要帮助使此类型适用于任何类型.
I need help with making this work for any type.
我有一个函数,我需要接受具有ID
属性的其他类型.
I have got a function I need to accept other types that have ID
property.
我尝试使用接口,但是在我的ID
属性案例中不起作用.这是代码:
I have tried using interfaces but that did not work for my ID
property case. Here is the code:
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)
}
我明白了
错误进展:39:无法将人类([Human]类型)用作[] Mammal类型,作为Count的参数
error prog.go:39: cannot use humans (type []Human) as type []Mammal in argument to Count
有关更多详细信息,请参见Go Playground,网址为 http://play.golang.org/p/xzWgjkzcmH
See Go Playground for more details here http://play.golang.org/p/xzWgjkzcmH
推荐答案
Use interfaces instead of concrete types, and use embedded interfaces so the common methods do not have to be listed in both types:
type Mammal interface {
GetID() int
GetName() string
}
type Human interface {
Mammal
GetHairColor() string
}
这是基于您的代码的这些接口的实现,这些代码使用嵌入式类型(结构):
And here is the implementation of these interfaces based on your code which uses embedded types (structs):
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()
函数中,您只能引用该方法,而不能引用实现的字段:
But then of course in your Count()
function you can only refer to the method and not the field of the implementation:
IDs[i] = strconv.Itoa(m.GetID()) // Access ID via the method: GetID()
并创建哺乳动物和人类的片段:
And creating your slices of Mammals and Humans:
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"},
}
这是> 游乐场 上的完整工作代码.
Here is the complete working code on Go Playground.
这篇关于Golang中的通用方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!