简体   繁体   English

将go嵌入式结构传递给函数

[英]Passing go embedded struct to function

I have something like this: 我有这样的事情:

type Foo struct{}
func NewFoo() *Foo { ... }

type Bar struct {
    *Foo
}

How can I pass an instance of Bar to a function that takes *Foo? 如何将Bar的实例传递给带有* Foo的函数?

func DoStuff(f *Foo) {}

func main() {
    bar := Bar{NewFoo()}
    DoStuff(bar) // <- go doesn't like this, type mismatch
}

Is it possible to get the embedded structure and pass it to the function? 是否有可能获得嵌入式结构并将其传递给函数?

The only way I can get this to work is if I treated *Foo as a member of the structure and passed it as bar.foo . 我可以使它bar.foo的唯一方法是,如果我将* Foo视为结构的成员并将其作为bar.foo传递。 But this is kind of messy, is that the only way? 但这有点混乱,这是唯一的方法吗?

Anonymous fields can be addressed by the name of the embedded type: 匿名字段可以通过嵌入类型的名称来寻址:

type Foo struct{}

type Bar struct {
    *Foo
}

bar := Bar{&Foo{}}

func(f *Foo) {}(bar.Foo)

See the Struct Types section in the language spec. 请参阅语言规范中的“ 结构类型”部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM