Go Struct

Go Tutorial

Go Struct – Complete Tutorial

In Go (Golang), a struct is a user-defined data type that allows you to group related data together.
It is similar to classes in OOP, but Go structs do not support inheritance.


 What is a Struct in Go?

A struct:

  • Groups multiple variables (fields) of different data types

  • Represents real-world entities

  • Is the foundation of Go data modeling

 Think of struct as a blueprint for data, not behavior.


 Why Use-Structs?

  •  Organize related data
  •  Create custom data types
  •  Improve code readability
  •  Used in APIs, JSON, databases
  • Essential for Go backend development

Basic-Struct Definition

Syntax

Example


 Creating & Using a Struct

Method-1: Declare then assign


Method 2: Structs Literal (Most Common)


Method 3: Without Field Names

 Order must match struct definition.


Access Structs Fields


Structs with Functions (Methods)

Method on Struct

Usage:

 This is how Go achieves OOP-like behavior.


Pointer to Structs (Very Important)

Passing struct by value copies data.
Use pointer to modify original struct.

  •  Memory efficient
  •  Interview favorite

 Anonymous Structs

 Useful for quick, temporary data


Nested Structs


 

Access:


Structs vs Map (Interview)

FeatureStructsMap
Type safetyYesNo
Fixed fieldsYesNo
PerformanceFasterSlower
JSON usageExcellentYes

 Use structs for fixed models, maps for dynamic data.


Structs with JSON (Real-World Use)

 Used in REST APIs


 Common Mistakes

  •  Forgetting to export fields (capital letters)
  •  Passing structs instead of pointer
  •  Using structs when map is better (or vice versa)
  •  Field order mistake in literals

Interview Questions & MCQs

Q1. What is a structs in Go?

A) Function
B) Package
C) User-defined data type
D) Interface

Answer: C


Q2. How do you access structs fields?

A) s->name
B) s[name]
C) s.name
D) s::name

Answer: C


Q3. Why use pointer to structs?

A) Faster compilation
B) Modify original data
C) Avoid syntax
D) Create copy

Answer: B


Q4. Can structs have methods?

A) Yes
B) No

Answer: A


Q5. Structs fields must be capitalized to?

A) Compile
B) Export outside package
C) Use pointer
D) Save memory

Answer: B


 Real-Life Use Cases

  • API request/response models
  •  Database records
  •  Configuration objects
  • Backend services
  •  Microservices

 Summary

  • Structs = custom data type in Go

  • Groups related fields

  • Supports methods (OOP-style)

  • Use pointers for performance

  • Widely used in APIs & backend

  • Must-know topic for Go interviews

You may also like...