My goal is to embed function to an existing type.
I am following Effective Go
The problem is it warns var parent *embedding.Parent github.com/kidfrom/learn-golang/embedding.Child struct literal uses unkeyed fields.
The current solution is to create NewChild(parent *Parent) *Child. However, I am afraid that this is just tricking the compiler and in the future it will panic unexpectedly, so what am I doing wrong?
func NewChild(parent *Parent) *Child { return &Child{parent} } cmd/test/main.go
package main import "github.com/kidfrom/learn-golang/embedding" func main() { parent := &embedding.Parent{} child := &embedding.Child{parent} // it warns `var parent *embedding.Parent github.com/kidfrom/learn-golang/embedding.Child struct literal uses unkeyed fields` child.CallParentMethod() } embedding.go
package embedding import "fmt" type Parent struct{} func (p *Parent) parentMethod() { fmt.Println("parent method") } type Child struct { *Parent } func (c *Child) CallParentMethod() { c.parentMethod() }