Go (Golang) / Object-Oriented Programming in Go

Working with Embedded Structs

This tutorial is about embedded structs in Go. We will explore how you can leverage embedding and composition to structure your Go code effectively.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores how Go implements object-oriented concepts using structs and interfaces.

Working with Embedded Structs in Go

1. Introduction

This tutorial aims to help you understand how to work with embedded structs in Go. By the end of this tutorial, you should be able to:

  • Understand what embedded structs are in Go
  • Understand how to use and create embedded structs
  • Leverage embedded structs for code organization and composition in Go

Prerequisites:
You should have a basic understanding of Go programming, including how to define and use structs.

2. Step-by-Step Guide

In Go, structs can contain other structs, and this concept is known as embedding. The idea behind this is instead of having a struct field with a name and type, you just specify the type. The struct you embed becomes a field of the struct it's included in, but without an explicit field name.

Best Practices:
- Use embedding for 'is-a' relationship, not 'has-a' relationship.
- Avoid embedding if it complicates your code. It should simplify and make your code more organized.

3. Code Examples

Example 1: Basic Example of Embedded Structs

package main

import "fmt"

// Defining a struct type
type Animal struct {
    Name string
    Age  int
}

// Another struct type with Animal as embedded field
type Dog struct {
    Breed string
    Animal
}

func main() {
    // Initializing Dog struct
    d := Dog{
        Breed: "Labrador",
        Animal: Animal{
            Name: "Max",
            Age:  5,
        },
    }

    fmt.Println(d)
}

In this example, Dog struct embeds the Animal struct. So, the Animal struct becomes a field in the Dog struct. The output of this program will be:

{Labrador {Max 5}}

Example 2: Accessing Fields of Embedded Structs

package main

import "fmt"

// Defining a struct type
type Animal struct {
    Name string
    Age  int
}

// Another struct type with Animal as embedded field
type Dog struct {
    Breed string
    Animal
}

func main() {
    // Initializing Dog struct
    d := Dog{
        Breed: "Labrador",
        Animal: Animal{
            Name: "Max",
            Age:  5,
        },
    }

    fmt.Println(d.Name)
    fmt.Println(d.Age)
    fmt.Println(d.Breed)
}

In this example, we access fields of the Animal struct directly from a Dog struct instance. The output will be:

Max
5
Labrador

4. Summary

In this tutorial, we have learned about embedded structs in Go. We've seen how to define them, how to create instances of structs with embedded structs, and how to access fields of embedded structs directly. Next, you can explore how to use embedded structs with interfaces for polymorphism.

Additional Resources:
- Go Documentation
- Effective Go

5. Practice Exercises

Exercise 1: Define a Circle struct that embeds a Point struct (with X and Y fields) and also has a Radius field. Create an instance of Circle, initialize it, and print its data.

Exercise 2: Extend the previous exercise by adding a method Area() to the Circle struct that calculates and returns the area of the circle. Print the area of the circle you created.

Solutions and explanations will be provided upon request.

Tips for Further Practice: Try to implement more complex programs using embedded structs. You can also explore the use of embedded interfaces in Go.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help