Go Program to Embed Structs

Introduction

In Go, struct embedding allows one struct type to include another struct type as an anonymous field. This provides a form of inheritance, where the embedded struct’s fields and methods become accessible directly from the outer struct. This guide will demonstrate how to embed structs in Go.

Problem Statement

Create a Go program that:

  • Defines two struct types, where one struct is embedded within another.
  • Initializes an instance of the outer struct.
  • Accesses and displays the fields of both the outer struct and the embedded struct.

Example:

  • Structs: Address with fields City and State, and Person with fields Name, Age, and an embedded Address.
  • Output:
    Name: John Doe, Age: 30, City: New York, State: NY
    

Solution Steps

  1. Define the Struct Types: Define two struct types, one of which will be embedded in the other.
  2. Import the fmt Package: Use import "fmt" for formatted I/O operations.
  3. Write the Main Function: Define the main function, which is the entry point of every Go program.
  4. Create and Initialize an Instance of the Outer Struct: Use a struct literal to create and initialize an instance of the outer struct.
  5. Access and Display the Fields: Use fmt.Println or fmt.Printf to display the values of the fields, including those from the embedded struct.

Go Program

package main

import "fmt"

// Step 1: Define the struct types
type Address struct {
    City  string
    State string
}

type Person struct {
    Name string
    Age  int
    Address // Embedding Address struct
}

/**
 * Go Program to Embed Structs
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 2: Create and initialize an instance of the outer struct
    person := Person{
        Name: "John Doe",
        Age:  30,
        Address: Address{
            City:  "New York",
            State: "NY",
        },
    }

    // Step 3: Access and display the fields of the outer and embedded structs
    fmt.Printf("Name: %s, Age: %d, City: %s, State: %s\n", person.Name, person.Age, person.City, person.State)
}

Explanation

Step 1: Define the Struct Types

  • The Address struct is defined with two fields: City and State, both of type string.
  • The Person struct is defined with three fields: Name of type string, Age of type int, and an embedded Address struct.

Step 2: Create and Initialize an Instance of the Outer Struct

  • An instance of the Person struct is created and initialized using a struct literal. The embedded Address struct is initialized within the Person struct:
    person := Person{
        Name: "John Doe",
        Age:  30,
        Address: Address{
            City:  "New York",
            State: "NY",
        },
    }
    

Step 3: Access and Display the Fields

  • The fields of both the Person struct and the embedded Address struct are accessed directly through the person instance. Since Address is embedded, its fields can be accessed directly as if they were part of Person:
    fmt.Printf("Name: %s, Age: %d, City: %s, State: %s\n", person.Name, person.Age, person.City, person.State)
    

Output Example

Example Output:

Name: John Doe, Age: 30, City: New York, State: NY

Example with Different Values:

person := Person{
    Name: "Alice Smith",
    Age:  25,
    Address: Address{
        City:  "San Francisco",
        State: "CA",
    },
}

Output:

Name: Alice Smith, Age: 25, City: San Francisco, State: CA

Example with Additional Fields in the Outer Struct:

If you add more fields to the Person struct, they can be accessed similarly:

type Person struct {
    Name    string
    Age     int
    Address // Embedding Address struct
    Phone   string
}

person := Person{
    Name: "John Doe",
    Age:  30,
    Address: Address{
        City:  "New York",
        State: "NY",
    },
    Phone: "123-456-7890",
}

fmt.Printf("Name: %s, Age: %d, City: %s, State: %s, Phone: %s\n", person.Name, person.Age, person.City, person.State, person.Phone)

Output:

Name: John Doe, Age: 30, City: New York, State: NY, Phone: 123-456-7890

Conclusion

This Go program demonstrates how to embed structs, allowing one struct to include another as an anonymous field. It covers basic programming concepts such as struct embedding, accessing embedded fields, and struct initialization in Go. This example is useful for beginners learning Go programming and understanding how to model complex data structures by composing multiple structs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top