Yesterday we learned that structs can have embedded fields. Although we didn’t really learn about any of the special powers this gives us. Today we’ll have a look at those powers.
One advantage to using an embedded type is that the implicit field name (the one derrived from the type, Person
, in our example) can be omitted. This is the result of “promotion”. For example:
var e Employee
e.Name = "Bob" // equivalent to e.Person.Name = "Bob"
e.Age = 42 // equivalent to e.Person.Age = 42
Struct types
…
A field or method
f
of an embedded field in a structx
is called promoted ifx.f
is a legal selector that denotes that field or methodf
.
Wait, what?
This is just saying that the fields Name
and Age
, from the examples above, are called promoted fields.
Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
As convenient as promoted fields are, they are not applicable for composite literals:
// Invalid, because Name and Age are promoted fields.
e1 := Employee{
Name: "Bob",
Age: 42,
}
// Valid, must include the literal Person value as well.
e2 := Employee{
Person: Person{
Name: "Bob",
Age: 42,
},
}
Quotes from The Go Programming Language Specification Version of December 15, 2022