亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不能將子項(類型 []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 關注
  • 258 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號