Chapter 46: Go Struct

1. What is a Struct? (The Simplest Explanation)

A struct is:

A named collection of fields — each field has its own name and type. You use a struct when you want to group related data together into one logical unit.

Think of it as a record or a row in a table or a form:

  • A Person has name, age, city
  • A Book has title, author, pages, year
  • An Order has id, items, total, status

2. Basic Syntax – How to Define & Create a Struct

Go

Very important style rule (2025–2026 community standard):

  • Always use field names when initializing (Person{Name: “…”}) — positional style is error-prone and non-idiomatic when struct has >2–3 fields
  • Use zero value when you want defaults
  • Use %+v in fmt.Printf to see field names (very helpful when debugging)

3. Accessing & Modifying Fields

Go

Dot notation — same as most languages.

4. Embedding (Composition – Go’s way of “inheritance”)

Go has no classical inheritance, but you can embed one struct inside another — this is called embedding or composition.

Go

Embedding rules (very important):

  • You can access embedded fields directly on the outer struct (called field promotion)
  • If there is a name conflict → you must use the full path (emp.Address.City)
  • Methods of embedded types are also promoted (we’ll see methods later)

5. Struct Pointers – When & Why

Most of the time you work with pointers to structs — especially when:

  • You want to modify the struct inside a function
  • You want to avoid copying large structs
Go

Common pattern:

Go

6. Anonymous Structs (Inline / One-off)

Sometimes you need a struct just once — no need to give it a name.

Go

Very common in:

  • JSON responses
  • Test data
  • Quick grouping

7. Real-World Patterns You Will Use Every Day

Go

8. Quick Practice – Try Writing These

  1. Define a Book struct: Title, Author, Pages, Year, IsRead
  2. Create a function printBook(b Book) that prints nicely
  3. Create promoteEmployee(e *Employee) that increases salary by 10%
  4. Embed Address inside Student struct and access city directly

Which struct felt most natural to design?

Any part still confusing?

  • Difference between value receiver vs pointer receiver? (we’ll see in methods)
  • When to use embedding vs plain field?
  • Anonymous structs vs named structs?
  • Or ready to move to methods (functions on structs) next?

Keep creating small structs and printing them — structs are the foundation of almost every meaningful data model in Go.

You’re making really solid progress — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *