在Go语言中传递带有匿名字段的结构体。

huangapple go评论78阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年2月8日 07:44:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/21639794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定