In Go, you can create and work with nested embedded structs by defining a struct type and embedding it within another struct type. Here's an example to help you understand how to do this:
package main
import "fmt"
// Define a struct type for Address
type Address struct {
Street string
City string
Country string
}
// Define a struct type for Person
type Person struct {
Name string
Age int
Address Address
}
func main() {
// Create an instance of the Person struct
p := Person{
Name: "John Doe",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
Country: "USA",
},
}
// Access and modify nested fields
fmt.Println("Name:", p.Name)
fmt.Println("Age:", p.Age)
fmt.Println("Address:", p.Address)
fmt.Println("Street:", p.Address.Street)
// Update nested field
p.Address.Street = "456 Elm St"
fmt.Println("Modified Street:", p.Address.Street)
}
In the above example, we define two struct types: Address
and Person
. The Person
struct embeds the Address
struct as one of its fields.
To create a nested embedded struct, you can simply provide a value of the embedded struct as a field within the enclosing struct. In this case, we provide an Address
value as the Address
field of the Person
struct.
You can access and modify the nested fields using dot notation (p.Address.Street
). In the example, we print out the values of various fields and modify the Street
field of the Address
struct.
Keep in mind that embedded structs are not the same as inheritance in traditional object-oriented programming. The embedded struct fields are accessible directly on the enclosing struct.