Explain the use of Go's struct types for grouping and organizing data?
In Go, a struct is a composite data type that groups together zero or more values with different types. It is similar to a class in other object-oriented programming languages. Each value in a struct is called a field.
To define a struct type in Go, we use the **type**
keyword followed by the name of the struct and the list of fields enclosed in curly braces. For example:
type Person struct {
name string
age int
}
In this example, we have defined a struct type called **Person**
with two fields: **name**
of type **string**
and **age**
of type **int**
.
We can create a new instance of the **Person**
struct by using the Person
type as a constructor function and providing values for its fields, like this:
p := Person{name: "John", age: 30}
We can access the fields of a struct using the dot notation, like this:
fmt.Println(p.name) // Output: John
fmt.Println(p.age) // Output: 30
We can also create anonymous structs, which are structs without a defined type, like this:
p := struct {
name string
age int
}{name: "John", age: 30}
Structs can also have methods associated with them, just like classes in other object-oriented programming languages. These methods are functions that have a receiver of the struct type, which means they can access and modify the fields of the struct.
Here's an example:
func (p *Person) isAdult() bool {
return p.age >= 18
}
fmt.Println(p.isAdult()) // Output: true
In this example, we have defined a method called **isAdult**
on the **Person**
struct, which returns a boolean indicating whether the person is an adult (i.e., 18 years or older). The **Person**
syntax indicates that the method has a pointer receiver, which means it can modify the fields of the **Person**
struct.