Home > Software engineering >  struct literal uses unkeyed fields
struct literal uses unkeyed fields

Time:09-24

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()
}

CodePudding user response:

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}

CodePudding user response:

You can fix the warning by adding a key to your *Parent attribute within the Child struct. Example:

type Child struct {
    Parent *Parent
}

and adjust the initialization of your child attribute in your main func as followed:

child := &embedding.Child{Parent: parent}
  •  Tags:  
  • go
  • Related