This question already has an answer here:
How do I initialize a composed struct in Go? (1 answer)
Closed 8 months ago.
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.
share improve this question follow
56.2k1313 gold badges8787 silver badges128128 bronze badges
asked Mar 4 at 3:51
46488 silver badges1818 bronze badges
-
2
Does How do I initialize a composed struct in Go? or nested struct initialization literals answer your question? – Muffin Top Mar 4 at 4:03
1 Answer
10
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