How to create and use nested struct in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to create and use nested struct using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import "fmt"
type Contact struct {
email string
phone string
}
type Person struct {
name string
age int
contact Contact // nested struct
}
func main() {
// create an instance of Person struct with nested Contact struct
person := Person{
name: "John",
age: 30,
contact: Contact{
email: "john@example.com",
phone: "555-1234",
},
}
// access the fields of nested Contact struct
fmt.Println("Person name:", person.name)
fmt.Println("Person age:", person.age)
fmt.Println("Person email:", person.contact.email)
fmt.Println("Person phone:", person.contact.phone)
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
In this program, we have defined two struct types: Person and Contact.
The Person struct includes a contact field of type Contact, which is a nested struct.
In the main function, we create an instance of the Person struct and initialize its fields,
including the contact field, which is initialized with a Contact struct.
We can then access the fields of the Contact struct using the dot notation on the Person struct instance.
As we can see, the fields of the Contact struct are accessible through the contact field of the Person struct, thanks to nesting.
#go #goprogramming #golang #golangtutorial #golanguage