struct - 在 Go 中传递具有匿名字段的结构

标签 struct go

这里是新手。我有两个结构,父级和子级。 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/

相关文章:

swift - 我可以将关联对象添加到 Swift Struct 吗?

c - 尝试将一个结构体的字段复制到 c 中的另一个结构体?

postgresql - 关于带变量的 Go sql 查询,我没有得到什么?

map 某部分的Golang for循环

c - 获取有关 C 类型结构体成员的信息(类型、值...等)

c - 难以访问嵌套的 C union 成员

C++,改变属于一个类的结构对象的值

arrays - Append for array of maps raplaces all previous array items on the 最新的一个

http - 使用 "+="缓慢构建长字符串

go - 获取/文章/:article_id Not working Gin-Gonic/Gin