Go Structs

Go Structs

Kishore V


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:

type StructName struct { field1 datatype field2 datatype field3 datatype }

Example: Defining and Using a Struct

Here’s an example of a Student struct with different field types:

Student 1: Rahul 20 Computer Science 8.7 Student 2: Anita 22 Electronics 9.1

Accessing Struct Fields

Struct fields are accessed using the dot (.) operator:

s1.name s1.age

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.

Product: Laptop Price: 59999.99 Stock: 10 --- Product: Headphones Price: 1999.5 Stock: 50 ---


Our website uses cookies to enhance your experience. Learn More
Accept !