create a struct with a field of type struct in go

To create a struct with a field of type struct in Go, you can simply define one struct within another. This is known as a nested struct.

Here's an example:

main.go
type Address struct {
    Street     string
    City       string
    State      string
    PostalCode string
}

type Person struct {
    Name    string
    Age     int
    Address Address
}
191 chars
13 lines

In this example, the Person struct has a field called Address which is of type Address. The Address struct has four fields: Street, City, State, and PostalCode.

To create a new Person object, you can initialize it like this:

main.go
p := Person{
    Name: "John Smith",
    Age:  30,
    Address: Address{
        Street:     "123 Main St",
        City:       "Anytown",
        State:      "CA",
        PostalCode: "12345",
    },
}
203 chars
11 lines

In this example, the Address field is initialized using the nested struct syntax. And you can access fields of the nested struct like this:

main.go
fmt.Println(p.Address.City) // prints "Anytown"
48 chars
2 lines

related categories

gistlibby LogSnag