How to fix “cannot use promoted field in struct literal of type” in Golang
In this article we are going to cover a common mistake Go developers make when working and initialising with Go embedded structs. Let’s see the example below
package main
import (
"fmt"
)
type Person struct {
Name string
}
type Employee struct {
Person
Company string
}
func main() {
fmt.Printf("%+v", Employee{Name: "bob", Company: "google"})
}
The expected output is the following. You can also try run the example yourself in the Go playground https://play.golang.org/p/4CaDJTrGlxv
./prog.go:17:29: cannot use promoted field Person.Name in struct literal of type Employee
How to initialise embedded struct fields in Go?
Following from the example above the solution is to explicitly define the embedded struct fields as follows
package main
import (
"fmt"
)
type Person struct {
Name string
}
type Employee struct {
Person
Company string
}
func main() {
fmt.Printf("%+v", Employee{Person: Person{Name: "bob"}, Company: "google"})
}
This is the expected output. You can try run this example yourself in the Go playground https://play.golang.org/p/uj0JWQSOwqY
{Person:{Name:bob} Company:google}
This is also being reported in a Go issue and there is an open proposal to make such initialisations more explicit https://github.com/golang/go/issues/9859
proposal: spec: direct reference to embedded fields in struct literals