为了账号安全,请及时绑定邮箱和手机立即绑定

不能将子项(类型 []Child)用作 func 参数中的类型 []Node

不能将子项(类型 []Child)用作 func 参数中的类型 []Node

C#
开心每一天1111 2021-12-07 19:44:45
这是我的测试代码package mainimport "fmt"type Node interface {    sayHello()}type Parent struct {    Name string}type Child struct {    Parent    Age int}type Children []Childfunc (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) 没有成功......
查看完整描述

1 回答

?
千万里不及你

TA贡献1784条经验 获得超9个赞

与接口数组(例如[]Child)相比,结构数组(例如)具有非常不同的内存布局[]Node。这样下去没有做[]Child,以[]Node转换含蓄,你必须做你自己:


nodes := make([]Node, len(children), len(children))

for i := range children {

    nodes[i] = children[i]

}

sayHellos(nodes)

顺便说一句,在您提供的示例中,sayHello直接调用会更有效:


for _, child := range children {

    child.sayHello()

}

可能这也是你应该在你的程序中做的事情。


查看完整回答
反对 回复 2021-12-07
  • 1 回答
  • 0 关注
  • 217 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信