Go Tutorial: Structs
Group related data under one name. Build the building blocks of every real-world Go program.
The building blocks of real programs
You have stored individual values in variables. A string here, an int there.
But real data does not come in pieces. A person has a name, an age, an email, and a city — all at once. A product has a title, a price, a stock count, and a category.
A struct lets you group related fields into a single, named type. It is the closest thing Go has to a class, and it is one of the most important things you will ever learn.
Fifteen steps. Build up to a full contact book.
What you'll learn in this Go structs tutorial
This interactive Go tutorial has 15 hands-on exercises. Estimated time: 28 minutes.
- What is a struct — Imagine a contact card. One card holds a person's name, their phone number, their email — all related, all together.
- Define a struct — The syntax for defining a struct is:
- Access fields with dot notation — To read a specific field, use a dot: `person.Name`, `person.Age`.
- Update a field — Fields work like variables. You can reassign them after creation.
- Zero values in structs — When you declare a struct without setting all fields, Go fills the rest with zero values — empty string for strings, 0 f…
- Struct as a function parameter — You can pass a struct into a function the same way you pass any value.
- Struct as a return value — Functions can return structs too.
- Pointer to a struct — When you pass a struct normally, Go copies it. Changes inside the function are lost.
- Nested structs — A struct can contain another struct as a field.
- Anonymous struct — Sometimes you need a struct for one specific thing and do not need to reuse it. An anonymous struct has no type name — i…
- Slice of structs — In real programs you rarely have just one struct. You have a list of them — a slice of structs.
- Methods — A method is a function attached to a struct. Instead of `printPerson(p)` you write `p.Print()`.
- Pointer receiver methods — A method with a pointer receiver can modify the struct it is attached to.
- Struct tags — Struct tags are metadata attached to fields. They tell encoding libraries how to handle each field.
- Build a contact book — No starter code.
Go Structs concepts covered
- The building blocks of real programs