Struct Embedding in Go

From the Go cheat sheet · Data Types & Structures · verified Jul 2026

Struct Embedding

Composition via embedding structs and interfaces

go
// Embed struct for composition
type Address struct {
    City    string
    Country string
}

type Person struct {
    Name string
    Address  // Embedded (promoted fields)
}

p := Person{
    Name:    "Alice",
    Address: Address{City: "NYC", Country: "US"},
}
fmt.Println(p.City) // "NYC" (promoted)
🎯 Go uses composition over inheritance via embedding
💡 Embedded fields and methods are promoted to outer struct
📌 Access via p.City or p.Address.City — both work
⚡ Interfaces can embed other interfaces for composition

More Go tasks

Back to the full Go cheat sheet