Nested struct in golang
- User
Nested struct in golang
- Assistant
In Go, a struct is a user-defined data type that represents a collection of fields. A nested struct is a struct type that contains fields that are themselves structs.
Here's an example:
type Address struct { Street string City string State string Zip int } type Person struct { FirstName string LastName string Age int Address Address }In this example, the
Personstruct contains a field calledAddresswhich is of typeAddress. TheAddressstruct has its own fields (Street,City,State,Zip) that represent the person's address.To access the fields of a nested struct, you can use dot notation like this:
p := Person{ FirstName: "John", LastName: "Doe", Age: 30, Address: Address{ Street: "123 Main St", City: "Anytown", State: "CA", Zip: 12345, }, } fmt.Println(p.FirstName) fmt.Println(p.Address.City)This will output:
John Anytown - User
Difference between embedded and struct in golang
- Assistant
In Go, a struct is a user-defined data type that represents a collection of fields. An embedded struct is a way to include one struct type as a field in another struct type.
Here's an example of a struct:
type Person struct { FirstName string LastName string Age int }Here's an example of an embedded struct:
type Address struct { Street string City string State string Zip int } type Person struct { FirstName string LastName string Age int Address }In this example, the
Personstruct includes an embeddedAddressstruct. This means that the fields of theAddressstruct are promoted to thePersonstruct, so you can access them directly from aPersonvariable.Here's an example of how to use an embedded struct:
p := Person{ FirstName: "John", LastName: "Doe", Age: 30, Address: Address{ Street: "123 Main St", City: "Anytown", State: "CA", Zip: 12345, }, } fmt.Println(p.FirstName) fmt.Println(p.City)This will output:
John AnytownThe main difference between a struct and an embedded struct is that an embedded struct is a way to include one struct type as a field in another struct type, while a struct is a standalone data type. An embedded struct promotes the fields of the embedded struct to the outer struct, while a struct does not.