【发布时间】:2015-02-08 10:59:42
【问题描述】:
我需要帮助才能使这项工作适用于任何类型。
我有一个函数需要接受具有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)
}
我明白了
error prog.go:39: cannot use human (type []Human) as type []Mammal in argument to Count
更多详情请参见 Go Playground http://play.golang.org/p/xzWgjkzcmH
【问题讨论】:
标签: generics go struct interface