Go Structs
In Go, a struct (short for structure) is a composite data type used to group related data fields together. Unlike arrays or slices—which store multiple values of the same type—structs allow you to combine values of different data types into a single, meaningful unit.
Structs are commonly used to model real-world entities such as users, products, or records in a database.
Why Use Structs?
- Organize related data into a single variable
- Represent complex data models clearly
- Improve code readability and maintainability
- Enable structured data handling in functions and methods
Declaring a Struct
To define a struct in Go, use the type and
struct keywords:
Example: Defining and Using a Struct
Here’s an example of a Student struct with different field types:
Accessing Struct Fields
Struct fields are accessed using the dot (.) operator:
This makes it easy to read and update individual fields within a struct.
Passing Structs to Functions
Structs can be passed as arguments to functions, allowing you to operate on structured data efficiently.
