Struct field promotion

March 14, 2023

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 struct x is called promoted if x.f is a legal selector that denotes that field or method f.

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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Struct tags

Struct types … A field declaration may be followed by an optional string literal tag, which becomes an attribute for all the fields in the corresponding field declaration. An empty tag string is equivalent to an absent tag. The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored. struct { x, y float64 "" // an empty tag string is like an absent tag name string "any string is permitted as a tag" _ [4]byte "ceci n'est pas un champ de structure" } // A struct corresponding to a TimeStamp protocol buffer.


Struct method promotion

Yesterday we saw an example of struct field promotion. But methods (which we haven’t really discussed yet) can also be promoted. Struct types … Given a struct type S and a named type T, promoted methods are included in the method set of the struct as follows: If S contains an embedded field T, the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T.


Embedded struct fields

When I introduced structs last week, I skipped over one sentence. Today I’m going to address that. Struct types A struct is a sequence of named elements, called fields, each of which has a name and a type. Field names may be specified explicitly (IdentifierList) or implicitly (EmbeddedField). Within a struct, non-blank field names must be unique. We already saw how field names are expressed explicitly. But what is an embedded field?