Open In App

Embedded Structures in Golang

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the Go programming language, Embedded Structures are a way to reuse a struct’s fields without having to inherit from it. It allows you to include the fields and methods of an existing struct into a new struct. The new struct can add additional fields and methods to those it inherits.

Syntax:

type outer struct {

    inner struct {

        field1 string

        field2 int

    }

}

Example 1:

Go




package main
  
import (
    "fmt"
)
  
type Address struct {
    City  string
    State string
}
  
type Person struct {
    Name    string
    Address //embedded struct
}
  
func main() {
    p := Person{
        Name: "John Doe",
        Address: Address{
            City:  "New York",
            State: "NY",
        },
    }
  
    fmt.Println("Name:", p.Name)
    fmt.Println("City:", p.City)
    fmt.Println("State:", p.State)
}


Output:

Name: John Doe
City: New York
State: NY

Explanation: This program defines two structs – Address and Person. The Person struct includes the Address struct. In the main function, a Person named “John Doe” is created with an address of “New York, NY”. The program then prints out the person’s name, city, and state. Because the Address struct is included in the Person struct, we can access the person’s city and state directly from the Person struct using dot notation. The program simply creates a person object with an address and prints out some of their details.

Example 2:

Go




package main
  
import "fmt"
  
type Author struct {
    Name    string
    Branch  string
    Year    int
}
  
type HR struct {
    Author // Embedded Type
}
  
func main() {
    result := HR{
        Author: Author{
            Name:   "Dhruv",
            Branch: "IT",
            Year:   2024,
        },
    }
  
    fmt.Println("Details of Author")
     fmt.Println(result)
}


Output:

Details of Author
{{Dhruv IT 2024}}

Explanation: This program creates two structs – Author and HR. The HR struct includes the Author struct. An instance of the HR struct is created with a value of the Author field set to “Dhruv”, “IT”, and 2024. The program then prints the message “Details of Author” followed by the result variable value. The output shows the Author fields inside the HR struct with curly braces.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads