flooblebit
flooblebit

Reputation: 547

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?

Upvotes: 8

Views: 2542

Answers (1)

JimB
JimB

Reputation: 109318

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.

Upvotes: 12

Related Questions