Use nested structs and embedding
Use nested structs and embedding
A nested named field stores another struct under an explicit field name. An embedded field declares a type without a separate field name; its unqualified type name becomes the field name. Embedding can promote selectors, but it does not make the outer type a subtype of the inner type.
package main
import ( "fmt")
type Address struct{ City string }type Customer struct { Name string Home Address}type Office struct { Address Floor int}
func main() { c := Customer{Name: "Ada", Home: Address{City: "Baku"}} o := Office{Address: Address{City: "Stockholm"}, Floor: 2} fmt.Println(c.Home.City) fmt.Println(o.Address.City, o.City)}Home is an ordinary named field, so the selector must include Home. Office embeds Address, making City reachable by either o.Address.City or the promoted o.City. The embedded field itself is still a value stored inside Office.
Expected output:
BakuStockholm StockholmSelect the embedded value explicitly
package main
import ( "fmt")
type Position struct{ X, Y int }type Robot struct { Position Name string}
func show(p Position) { fmt.Println(p.X, p.Y) }func main() { r := Robot{Position: Position{X: 4, Y: 7}, Name: "R"} show(r.Position)}show expects Position, not Robot. Pass r.Position explicitly; embedding does not make Robot assignable to Position. A promoted field cannot be used directly as a key in the outer composite literal.
Expected output:
4 7Try it locally
Define Contact with Email string and Member embedding Contact plus ID int. Initialize ID 7 and Email "a@example.com" using nested literals; print member.ID and member.Email.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Structs and defined types 04: Use nested structs and embedding
Check the lesson objective before moving on.
Which key initializes embedded Address in Office?
Can a Robot embedding Position be assigned directly to a Position variable?