{ } FIELD NOTES / GOPODCAST COMPANION · 10–12 MIN
Back to Go Examples
A guided Go walkthrough

Structs make
data feel together.

Follow one library book from a handful of fields to methods, interfaces, collections, JSON, and concurrent code. Along the way, see exactly when Go copies a value—and when two names point at the same thing.

Start with the shape9 stops · ~12 minutes · no setup
A TYPE DESCRIBES THE SHAPE
type Book structVALUE
Titlestring "Dune"
Authorstring "Frank Herbert"
Pagesint 412
Borrowedfalse
ONE VALUE · FOUR RELATED FIELDS
YOUR WALKTHROUGH · 0%
SCROLL TO EXPLORE
01 · The shape

A struct is a named bundle of fields.

Think of a struct as a form whose fields have names and types. The type describes the form; a value is one filled-in form.

book.go
type Book struct {
    Title    string
    Author   string
    Pages    int
    Borrowed bool
}

Each field has its own type. Access it with a dot: book.Title. Go checks field types at compile time, so book.Pages = "many" is rejected before the program runs.

Keep this picture: one Book value groups facts that belong to the same book. The fields do not have to share a type.
Quick check

What does the Book type define?

02 · Make a value

Fill in a book—or start at zero.

A keyed struct literal names each field, so it stays readable as the type grows. Unspecified fields receive their zero value: empty string, 0, false, or the appropriate zero for that type.

keyed literal · zero values
book := Book{
    Title:  "The Left Hand of Darkness",
    Author: "Ursula K. Le Guin",
    Pages:  304,
}
// Borrowed is false: its zero value.
var draft Book
// draft.Title == "", draft.Pages == 0

Zero values make Go values ready to use, but “initialized” does not mean “valid for my app.” A library might require a non-empty title and positive page count. A regular function can check those rules:

validation is your rule
func NewBook(title, author string, pages int) (Book, error) {
    if title == "" || pages <= 0 {
        return Book{}, errors.New("title and positive pages required")
    }
    return Book{Title: title, Author: author, Pages: pages}, nil
}
No special constructor syntax: NewBook is an ordinary function by convention. It is useful when construction needs validation or setup.
03 · Copy & pointers

Assignment copies the struct value.

For our fields—strings, an integer, a boolean—copying a Book makes a separate value. Change one copy, and the other keeps its old Borrowed field.

Original book

book.Borrowed = false
Borrowed: false

Copied book

copy := book
Borrowed: false

Click the button: it changes copy.Borrowed, while book.Borrowed stays false. To let a function update the original, pass its address with &:

pointer parameter
func markBorrowed(b *Book) {
    b.Borrowed = true
}
markBorrowed(&book)

The function receives a copy of the pointer; that pointer still refers to the same book. Go passes arguments by value, including pointers.

One subtle detail: a struct copy copies its fields. If a field is a slice or map, the copied field still refers to shared underlying data. A copied Book with Tags []string may share tag elements. Copy those elements too when you need independent data.
Quick check

If a Book has a slice field, what might remain shared after copying the Book?

04 · Methods & interfaces

Attach behavior to the type.

A method is a function with a receiver: the value it operates on. A value receiver works on a copy; a pointer receiver can update the original book.

methods on Book
func (b Book) Description() string {
    return b.Title + " by " + b.Author
}
func (b *Book) Borrow() error {
    if b.Borrowed { return errors.New("already borrowed") }
    b.Borrowed = true
    return nil
}

Use a pointer receiver when the method must mutate the value, or when avoiding a large copy is appropriate. It does not automatically make code faster or safe for concurrent use.

Interfaces ask for behavior

An interface describes the methods a value must have. A Book with Description() string satisfies Describer automatically—there is no implements declaration.

implicit interface satisfaction
type Describer interface {
    Description() string
}
func PrintDescription(d Describer) {
    fmt.Println(d.Description())
}
Receiver detail: if Description has a pointer receiver, *Book satisfies Describer; a plain Book value does not. Convenient method calls do not change interface satisfaction rules.
05 · Build with parts

Compose small types into a bigger idea.

A library can contain books, author records, and a storage service. This is composition: a larger type uses smaller types as fields.

composition & embedding
type Author struct { Name string }
type Library struct {
    Books []Book
    Keeper Author
}
// Embedding promotes fields and methods (with name-conflict rules).
type FeaturedBook struct {
    Book
    Badge string
}

Embedding is a convenience for reaching promoted fields and methods. It is not class inheritance: a FeaturedBook is not interchangeable with a Book.

Packages add another boundary. Uppercase names are exported; lowercase names stay within their package. Keep state private when callers should use methods that enforce rules.

06 · Collections

Put books in slices and maps.

Slice: ordered, resizable

Append values and loop through them. A range variable is a copy of the element.

Map: look up by key

Read a Book, change the local value, then assign it back—or store pointers.

range gives you a copy
books := []Book{first, second}
for _, book := range books {
    book.Borrowed = true // changes the copy
}
for i := range books {
    books[i].Borrowed = true // changes the slice element
}
byID := map[string]Book{"bk-1": first}
b := byID["bk-1"]
b.Borrowed = true
byID["bk-1"] = b // write changed value back
Want to…UseRemember
Keep an ordered list[]BookRange values are copies
Find by identifiermap[string]BookAssign a changed value back
Identify a shelf positionmap[Location]BookEvery Location field must be comparable

A struct can be a map key if all its fields are comparable. A struct containing a slice or map cannot be a key.

Quick check

Inside a range loop, how do you update the Book stored in a slice?

07 · Errors & JSON

Let structs carry useful details.

An operation can return an error for the caller to handle. When the error needs structured details—like which book failed—a custom struct plus an Error() string method can satisfy Go’s error interface.

structured error
type BorrowError struct { BookID string }
func (e BorrowError) Error() string {
    return "cannot borrow book " + e.BookID
}

For JSON, encoding/json works with exported fields by default. Tags describe external names or omission behavior; the JSON package interprets them. Tags do not run validation.

JSON mapping metadata
type Book struct {
    Title    string `json:"title"`
    Author   string `json:"author"`
    Pages    int    `json:"pages"`
    Borrowed bool   `json:"borrowed"`
    Internal string `json:"-"`
}
var decoded Book
err := json.Unmarshal(data, &decoded) // pass a pointer
08 · Shared state

Shared memory needs shared rules.

Two goroutines accessing the same book through pointers can race if one writes while another reads or writes without synchronization. Structs do not add locks automatically.

mutex travels with protected data
type SafeBook struct {
    mu sync.Mutex
    Book
}
// Lock around every access that follows this protection rule.
s.mu.Lock()
s.Book.Borrowed = true
s.mu.Unlock()

A mutex must not be copied after first use, so a struct containing an active mutex should not be copied either. Such values are commonly used through pointers.

Channels can pass a request struct to a worker and receive a result struct. Sending a struct copies its value; sending a pointer copies the pointer. Slices, maps, pointers, and their referenced data may still be shared, so decide who owns mutation.

Coordination is not ownership: channels help organize communication, but a message containing references can still point at data another goroutine can modify.
09 · Keep building

A few more places structs shine.

Generics

A type parameter lets one struct hold different kinds of values. The compiler still checks the chosen type.

Tests

A slice of test-case structs keeps inputs and expected results together, making scenarios easy to add.

one container, different value types
type Shelf[T any] struct {
    Items []T
}
books := Shelf[Book]{Items: []Book{first}}
names := Shelf[string]{Items: []string{"Avery"}}

With Shelf[Book], Items is a slice of books; with Shelf[string], it is a slice of strings. The compiler checks each use. Interfaces are useful when behavior varies; generics are useful when a type or algorithm can work across types.

test cases as data
tests := []struct {
    name string
    borrowed bool
    wantErr bool
}{
    {"available book", false, false},
    {"already borrowed", true, true},
}
Your struct design checklist

Start with what belongs together.

Structs begin as a bundle of fields. Thoughtful methods, interfaces, collections, and ownership rules make them part of a reliable program.

↑