英文:
Passing struct with anonymous field in Go
问题
你好!以下是代码的翻译:
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()
函数的声明应该是:
func myfunc(data *Parent) {
fmt.Printf("Dad is %s\n", data.Dad)
}
将 data
参数的类型从 Parent
改为 *Parent
,这样函数就可以接收一个指向 Parent
结构体的指针作为参数,从而可以正确处理 Child
结构体。
英文:
Go newbie here. I have two structs, Parent and Child. Child contains Parent as an anonymous field. I want to know how I can pass that struct to a function which is expecting a Parent (and knows nothing about Child). Here's code illustrating what I want to do:
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)
}
What's the magic declaration of myfunc() to get this to work?
答案1
得分: 4
你的代码在Go Playground上可以运行,只需将倒数第二行改为:
myfunc(data.Parent)
你不应该期望仅通过更改myfunc
就能使其工作,因为你说myfunc
不能知道Child
类的任何信息。
英文:
Your code works on the Go playground if you just change the second-to-last line to:
myfunc(data.Parent)
You shouldn't expect to be able to make it work just be changing myfunc
since you said that myfunc
cannot know anything about the Child
class.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论