Embedded Structs
Embedding a Struct
Placing a struct type inside another struct without giving it a field name embeds it, and Go automatically promotes its fields so they can be accessed directly on the outer struct, without an extra dot.
Example: Embedding a Struct
package main
import "fmt"
type Address struct {
City, Country string
}
type Person struct {
Name string
Address
}
func main() {
p := Person{Name: "Kiran", Address: Address{City: "Pune", Country: "India"}}
fmt.Println(p.Name, p.City, p.Country)
}
Login to try C/C++/Java/PHP code in the editor
Accessing the Embedded Struct Directly
Even though fields are promoted, the embedded struct is still reachable as a whole through its type name, which is useful when you need to pass just that inner piece to another function.
Example: Accessing the Embedded Struct Directly
package main
import "fmt"
type Address struct {
City string
}
type Person struct {
Name string
Address
}
func main() {
p := Person{Name: "Meera", Address: Address{City: "Delhi"}}
fmt.Println(p.Address.City)
}
Login to try C/C++/Java/PHP code in the editor
Promoted Methods
If the embedded type has methods, those methods are promoted too, so the outer struct appears to have them directly -- this is Go's primary mechanism for sharing behavior between types.
Note: This is how Go achieves code reuse across types, without classical inheritance.
Example: Promoted Methods
package main
import "fmt"
type Engine struct {
Horsepower int
}
func (e Engine) Describe() string {
return fmt.Sprintf("%d hp engine", e.Horsepower)
}
type Car struct {
Engine
Model string
}
func main() {
c := Car{Engine: Engine{Horsepower: 300}, Model: "Speedster"}
fmt.Println(c.Model, "-", c.Describe())
}
Login to try C/C++/Java/PHP code in the editor
- Thinking embedding is inheritance like in Java/C++ -- it's composition; there's no polymorphism through an embedded type alone.
- Naming a regular field the same as an embedded type's promoted field, creating ambiguity that must be resolved explicitly.
- Forgetting that to access the embedded struct itself (not just its promoted fields), you use the type name as the field name.
- Embedding places one struct type inside another without naming the field explicitly.
- The embedded type's fields and methods are promoted -- accessible directly on the outer struct.
- Embedding is composition, not inheritance -- there's no runtime polymorphism from embedding alone.
- The embedded struct itself is still accessible via its type name as a field.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: