作者:zgshenxz_474 | 来源:互联网 | 2023-05-22 21:00
我需要帮助才能为任何类型的工作.
我有一个函数我需要接受其他具有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
1> Uvelichitel..:
你无法在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"},
}
...
}
这是工作的例子