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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With