Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing go embedded struct to function

Tags:

go

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?

like image 239
flooblebit Avatar asked Dec 02 '16 17:12

flooblebit


1 Answers

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.

like image 52
JimB Avatar answered Oct 20 '22 04:10

JimB