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 12 hands-on exercises. Estimated time: 28 minutes.
- What is a struct — Imagine a library catalog card. One card holds a book's title, its author, its ISBN — all related, all together.\nA stru…
- Define a struct — Define an `Author` struct with three fields: `Name` (string), `Nationality` (string), and `BirthYear` (int). Then create…
- achha — dot notation accesses fields — To read a specific field, use a dot: `book.Title`, `book.Pages`. You don't have to print the whole struct at once.\nPrin…
- Update a field — Fields work like variables. You can reassign them after creation.\n`b.Pages = 350` updates the Pages field directly.\nUp…
- 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 function parameter and return value — You can pass structs to functions and return them. When you pass a struct normally, Go makes a copy.\nCall `printBook` w…
- Pointer to a struct (avoid copies) — When you pass a struct normally, Go copies it. Use a pointer to pass the original.\n`func addPages(b *Book) { b.Pages +=…
- Nested structs — A struct can contain another struct as a field. A `Book` has an `Author`.\nRun this, then update `b.Author.Nationality` …
- Anonymous struct — Sometimes you need a struct for one specific thing and don't need to reuse it. An anonymous struct has no type name — de…
- Slice of structs — In real programs you rarely have just one struct. You have a list of them — a slice of structs.\n`books := []Book{{...},…
- Struct tags (JSON serialization) — Struct tags are metadata attached to fields. They tell encoding libraries how to handle each field.\n`type Book struct {…
- Build a library catalog — No starter code. Build a library catalog from scratch:\n1. Define an `Author` struct with `Name` (string), `Nationality`…
Go Structs concepts covered
- The building blocks of real programs