Explain the use of Go structs for defining custom data types?

In Go, a struct is a composite data type that allows you to group together variables of different types under a single name. You can think of a struct as a way to create your own custom data type that is made up of other data types.

Here is an example of a simple struct in Go:

type Person struct {
name string
    age int
    occupation string

In this example, we define a new struct called **Person**, which has three fields: **name**, **age**, and **occupation**. Each field has its own data type, which can be any built-in or custom data type.

To create a new instance of this struct, we can use the following syntax:

person1 := Person{"John Doe", 30, "Software Engineer"}

In this example, we create a new **Person** instance called **person1** and initialize its fields using a struct literal. We can also access and modify the fields of a struct using the dot notation:

fmt.Println( // Output: John Doe

person1.age = 31
fmt.Println(person1.age) // Output: 31

Structs are commonly used in Go to represent complex data structures such as database records, network packets, and more. They provide a flexible way to organize and manipulate data in a program.

Related Questions You Might Be Interested