Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct literal uses unkeyed fields

Tags:

go

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()
}
like image 289
kidfrom Avatar asked Feb 11 '26 04:02

kidfrom


1 Answers

The warning you are getting is most likely from go-staticcheck. You'd also see a similar warning by running:

$ go vet

./main.go:8:12: github.com/kidfrom/learn-golang/embedding.Child composite literal uses unkeyed fields

Checking the docs of the package you are importing:

$ go doc "github.com/kidfrom/learn-golang/embedding" Child

package embedding // import "github.com/kidfrom/learn-golang/embedding"

type Child struct {
        *Parent
}

func NewChild(parent *Parent) *Child
func (c *Child) CallParentMethod()

shows the embedded type within Child is Parent, so to fix the warning explicitly assign the value to this (embedded struct) field:

child := &embedding.Child{Parent: parent}
like image 114
colm.anseo Avatar answered Feb 14 '26 04:02

colm.anseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!