简体   繁体   中英

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?

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 . 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.

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.

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