In Go, you can embed a struct into another struct using anonymous fields. Here's an example:
package main
import "fmt"
type Address struct {
Street string
City string
ZipCode string
}
type Person struct {
Name string
Age int
Address // embedding Address struct here
}
func main() {
p := Person{
Name: "John",
Age: 30,
Address: Address{
Street: "123 Main St",
City: "New York",
ZipCode: "10001",
},
}
fmt.Println(p.Name) // Output: John
fmt.Println(p.Age) // Output: 30
fmt.Println(p.Address.Street) // Output: 123 Main St
fmt.Println(p.Address.City) // Output: New York
fmt.Println(p.Address.ZipCode) // Output: 10001
}
In this example, we have defined two structs: Address
and Person
. The Address
struct represents a person's address, and the Person
struct represents a person with their name, age, and address.
The Address
struct is embedded anonymously inside the Person
struct using the struct name as the field name. This allows the Person
struct to directly access the fields of the embedded Address
struct.
To create a new Person
object, you can initialize it with the desired fields, including the embedded Address
struct. You can then access the embedded fields using dot notation as shown in the main
function.