Menu
Coddy logo textTech

Embedded Structs

Part of the Fundamentals section of Coddy's GO journey — lesson 99 of 109.

Go allows you to embed one struct inside another, creating composition relationships. This is Go's approach to inheritance.

Define two structs, with one embedded in the other:

type Address struct {
    city  string
    state string
}

type Person struct {
    name string
    age  int
    Address  // embedded struct (no field name)
}

func main() {
    person := Person{
        name: "Alice",
        age: 30,
        Address: Address{city: "Portland", state: "Oregon"},
    }
    
    // Access fields directly
    fmt.Println(person.city)  // Access embedded field
}

The output shows we can access the embedded struct's fields directly:

Portland
challenge icon

Challenge

Beginner

In this challenge, you'll practice using embedded structs (composition) in Go.

We have two structs: Address and Person. The Person struct should embed the Address struct so that a person can directly access address fields.

Your task is to complete the Person struct definition to embed the Address struct, and then access the address fields directly from the person instance.

Cheat sheet

Go uses struct embedding for composition. Embed one struct inside another by including the struct type without a field name:

type Address struct {
    city  string
    state string
}

type Person struct {
    name string
    age  int
    Address  // embedded struct (no field name)
}

Access embedded struct fields directly:

person := Person{
    name: "Alice",
    age: 30,
    Address: Address{city: "Portland", state: "Oregon"},
}

fmt.Println(person.city)  // Access embedded field directly

Try it yourself

package main

import "fmt"

// Address struct contains location information
type Address struct {
	Street  string
	City    string
	ZipCode string
}

// Person struct should embed the Address struct
type Person struct {
	Name string
	Age  int
	// TODO: Embed the Address struct here (just one line)
}

func main() {
	// Create a new person with address information
	person := Person{
		Name: "Alice",
		Age:  30,
		Address: Address{
			Street:  "123 Main St",
			City:    "Wonderland",
			ZipCode: "12345",
		},
	}

	// Print person information including address
	fmt.Println("Name:", person.Name)
	fmt.Println("Age:", person.Age)
	
	// TODO: Print the address fields directly from the person instance
	// (without using person.Address.Street, etc.)
	fmt.Println("Street:", person.Street)
	fmt.Println("City:", person.City)
	fmt.Println("ZipCode:", person.ZipCode)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals