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:
Addresswith fieldsCityandState, andPersonwith fieldsName,Age, and an embeddedAddress. - Output:
Name: John Doe, Age: 30, City: New York, State: NY
Solution Steps
- Define the Struct Types: Define two struct types, one of which will be embedded in the other.
- Import the fmt Package: Use
import "fmt"for formatted I/O operations. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Create and Initialize an Instance of the Outer Struct: Use a struct literal to create and initialize an instance of the outer struct.
- Access and Display the Fields: Use
fmt.Printlnorfmt.Printfto 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
Addressstruct is defined with two fields:CityandState, both of typestring. - The
Personstruct is defined with three fields:Nameof typestring,Ageof typeint, and an embeddedAddressstruct.
Step 2: Create and Initialize an Instance of the Outer Struct
- An instance of the
Personstruct is created and initialized using a struct literal. The embeddedAddressstruct is initialized within thePersonstruct: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
Personstruct and the embeddedAddressstruct are accessed directly through thepersoninstance. SinceAddressis embedded, its fields can be accessed directly as if they were part ofPerson: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.