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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.