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.
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.
Book value groups facts that belong to the same book. The fields do not have to share a type.What does the Book type define?
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.
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 == 0Zero 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:
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
}NewBook is an ordinary function by convention. It is useful when construction needs validation or setup.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 = falseCopied book
copy := bookClick the button: it changes copy.Borrowed, while book.Borrowed stays false. To let a function update the original, pass its address with &:
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.
Book with Tags []string may share tag elements. Copy those elements too when you need independent data.If a Book has a slice field, what might remain shared after copying the Book?
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.
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.
type Describer interface {
Description() string
}
func PrintDescription(d Describer) {
fmt.Println(d.Description())
}Description has a pointer receiver, *Book satisfies Describer; a plain Book value does not. Convenient method calls do not change interface satisfaction rules.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.
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.
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.
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… | Use | Remember |
|---|---|---|
| Keep an ordered list | []Book | Range values are copies |
| Find by identifier | map[string]Book | Assign a changed value back |
| Identify a shelf position | map[Location]Book | Every 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.
Inside a range loop, how do you update the Book stored in a slice?
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.
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.
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 pointerShared 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.
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.
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.
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.
tests := []struct {
name string
borrowed bool
wantErr bool
}{
{"available book", false, false},
{"already borrowed", true, true},
}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.