error: cannot use promoted field in struct literal of type

Viewed 14665

I have two packages where Package B imports Package A, like this:

Package A

package A

type Car struct {
    Color       string
    Make        string
    Model       string
}

Package B

package B

type car struct {
    *A.Car
}

func NewCar() car {
    return &car{
        Color: "red",
        Make:  "toyota",
        Model: "prius"}
}

However, this gives me the error: cannot use promoted field Car.Color in struct literal of type car inside NewCar function, how do I fix this? Everything I have read online just makes me more confused.

1 Answers

You need:

func NewCar() *car {
    return &car{ &A.Car{
        Color: "red",
        Make:  "toyota",
        Model: "prius",
    }}
}

See https://github.com/golang/go/issues/9859 for:

proposal: spec: direct reference to embedded fields in struct literals

Related