0
0
Goprogramming~5 mins

Why structs are used in Go

Choose your learning style9 modes available
Introduction

Structs help group related information together in one place. They make it easier to organize and work with data that belongs together.

When you want to represent a real-world object like a person with name, age, and address.
When you need to keep different pieces of data related to each other, like a book's title, author, and pages.
When you want to pass multiple related values together in a function.
When you want to create a custom data type that holds several fields.
When you want to improve code readability by grouping data logically.
Syntax
Go
type StructName struct {
    Field1 FieldType1
    Field2 FieldType2
    // more fields
}

Each field has a name and a type.

Structs create a new data type you can use like any other type.

Examples
This defines a Person with a name and age.
Go
type Person struct {
    Name string
    Age  int
}
This defines a Book with title, author, and number of pages.
Go
type Book struct {
    Title  string
    Author string
    Pages  int
}
Sample Program

This program creates a Person struct, fills it with data, and prints the values.

Go
package main

import "fmt"

// Define a struct to hold person information
 type Person struct {
    Name string
    Age  int
}

func main() {
    // Create a new Person
    p := Person{Name: "Alice", Age: 30}

    // Print the person's details
    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
}
OutputSuccess
Important Notes

Structs help keep related data together, making your code easier to understand.

You can create many instances of a struct with different values.

Structs are like blueprints for creating objects with multiple properties.

Summary

Structs group related data into one unit.

They help organize and manage complex information.

Using structs makes your code clearer and easier to maintain.