← Back to Go Course | Chapter 6: Structs & Methods | Lesson 2 of 6

Embedded Structs

Embedding a struct inside another is like giving one form a built-in copy of another form's blanks, so the outer form automatically has all the inner one's fields too.

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

markup
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)
}

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

markup
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)
}

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

markup
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())
}
Common Mistakes
  1. Thinking embedding is inheritance like in Java/C++ -- it's composition; there's no polymorphism through an embedded type alone.
  2. Naming a regular field the same as an embedded type's promoted field, creating ambiguity that must be resolved explicitly.
  3. Forgetting that to access the embedded struct itself (not just its promoted fields), you use the type name as the field name.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.