这里是新手。我有两个结构,父级和子级。 Child 包含 Parent 作为匿名字段。我想知道如何将该结构传递给需要父级(并且对子级一无所知)的函数。下面的代码说明了我想要做什么:
package main
import "fmt"
type Parent struct {
Dad string
}
type Child struct {
Parent
Son string
}
func myfunc(data Parent) {
fmt.Printf("Dad is %s\n", data.Dad)
}
func main() {
var data Child
data.Dad = "pappy"
data.Son = "sonny"
myfunc(data)
}
myfunc() 的神奇声明是什么来让它工作?
最佳答案
您的代码works on the Go playground如果您只是将倒数第二行更改为:
myfunc(data.Parent)
您不应期望仅更改 myfunc
即可使其工作,因为您说过 myfunc
无法了解有关 Child
的任何信息> 类。
关于struct - 在 Go 中传递具有匿名字段的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639794/