这是我的测试代码
package main
import "fmt"
type Node interface {
sayHello()
}
type Parent struct {
Name string
}
type Child struct {
Parent
Age int
}
type Children []Child
func (p Parent) sayHello() {
fmt.Printf("Hello my name is %s\n", p.Name)
}
func (p Child) sayHello() {
fmt.Printf("Hello my name is %s and I'm %d\n", p.Name, p.Age)
}
func makeSayHello(n Node) {
n.sayHello()
}
func sayHellos(list []Node) {
for _, p := range list {
makeSayHello(p)
}
}
func main() {
children := []Child{Child{Parent: Parent{Name: "Bart"}, Age: 8}, Child{Parent: Parent{Name: "Lisa"}, Age: 9}}
for _, c := range children {
c.sayHello()
}
makeSayHello( Parent{"Homer"} )
sayHellos( []Node{Parent{"Homer"}} )
sayHellos( []Node{Parent{"Homer"},Child{Parent:Parent{"Maggy"},Age:3}} )
sayHellos( children ) // error : cannot use children (type []Child) as type []Node in argument to sayHellos
}
链接https://play.golang.org/p/7IZLoXjlIK
我不明白。假设我有一个 []Child 我无法修改,我想将它与接受 []Parent 的 un 函数一起使用。为什么我有类型错误?
如果我不能或不想通过更改此解决方案
children := []Child{...}
到
children := []Node{...}
我该怎么做才能将 []Child 转换为 []Node ?不是已经?我必须做另一个 []Node 来复制我的元素吗?我天真地尝试 children.([]Node) 或 []Node(children) 没有成功......
千万里不及你
相关分类