What is struct in Go: Definition and Usage Explained
struct is a custom data type that groups together related values called fields. It works like a container to hold different pieces of information under one name, similar to a real-world object with properties.How It Works
A struct in Go is like a blueprint for creating objects that hold multiple pieces of data. Imagine a car: it has properties like color, brand, and speed. A struct lets you bundle these properties together in one place.
Each property inside a struct is called a field, and each field has a name and a type. When you create a struct variable, you get a single value that contains all these fields. You can then access or change each field separately.
This helps organize data clearly and makes your program easier to understand and maintain, especially when dealing with complex information.
Example
This example shows how to define a struct named Person with fields for name and age, then create and use a variable of that type.
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{Name: "Alice", Age: 30} fmt.Println("Name:", p.Name) fmt.Println("Age:", p.Age) }
When to Use
Use structs when you want to group related data together to represent something meaningful in your program. For example, you can use structs to represent a user profile, a product in a store, or a point on a map.
Structs are especially useful when you need to pass multiple related values around your program as a single unit or when you want to organize data clearly for better readability and maintenance.
Key Points
- A
structgroups multiple fields into one data type. - Each field has a name and a type.
- Structs help organize complex data clearly.
- You create variables of struct type to hold related information.
- Access fields using dot notation (e.g.,
p.Name).