0
0
GoConceptBeginner · 3 min read

What is struct in Go: Definition and Usage Explained

In Go, a 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.

go
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)
}
Output
Name: Alice Age: 30
🎯

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 struct groups 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).

Key Takeaways

A struct in Go groups related data fields into one custom type.
Use structs to represent real-world objects or complex data clearly.
Access struct fields with dot notation to read or modify values.
Structs improve code organization and readability.
Define structs with the type keyword followed by field definitions.