13

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
JAM
  • 740
  • 3
  • 15
  • 33
  • 2
    Does [How do I initialize a composed struct in Go?](https://stackoverflow.com/questions/44123399/how-do-i-initialize-a-composed-struct-in-go) or [nested struct initialization literals](https://stackoverflow.com/questions/19325496/nested-struct-initialization-literals) answer your question? – Charlie Tumahai Mar 04 '20 at 04:03

1 Answers1

18

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

Shang Jian Ding
  • 1,931
  • 11
  • 24