Prove your Go code works: table-driven tests & subtests, helpers like t.Cleanup, t.Parallel and TestMain, mocks & fakes via interfaces, benchmarks with pprof, plus fuzzing and the race detector.
We are building the API for a parcel tracking system: every shipment has an ID, a destination city, a weight, and a fragile flag. Without a custom type you drag four loose variables through every function — and nothing keeps together what belongs together. That is exactly what structs are for: they bundle related data under a single named type.
In Go, almost everything we touch daily — API payloads, configuration, database rows — is at heart a struct. Model your structs well and you have modeled the data of your entire application. This module lays the foundation: first the values themselves, then methods on them, then composition, construction, and finally the JSON wire format.
package main
import "fmt"
// Package bundles all data of a single shipment
type Package struct {
ID string
City string
Weight float64
Fragile bool
}
func main() {
// Keyed literal: field names explicit, order does not matter — the Go idiom
p1 := Package{ID: "DE-104", City: "Berlin", Weight: 2.4, Fragile: true}
// Unkeyed literal: positional — silently breaks when someone reorders fields
p2 := Package{"DE-207", "Hamburg", 0.8, false}
fmt.Printf("%s goes to %s (%.1f kg)\n", p1.ID, p1.City, p1.Weight)
fmt.Println(p2.Fragile)
}
// → DE-104 goes to Berlin (2.4 kg)
// → false
The Zero Value Is Usable Immediately
var p Package is not an error state: every field starts with its zero value — "" for strings, 0 for numbers, false for booleans. A freshly declared struct is valid without any constructor. Only fields of type slice, map, or pointer need initialization before first use.
Two struct values may be compared with ==, field by field — not by reference. The rule: this works only as long as every field is comparable. Strings, numbers, booleans, and pointers are; slices, maps, and functions are not.
func main() {
var p Package
fmt.Printf("%q %.1f %v\n", p.ID, p.Weight, p.Fragile)
// → "" 0.0 false
a := Package{ID: "DE-104", City: "Berlin"}
b := Package{ID: "DE-104", City: "Berlin"}
fmt.Println(a == b)
// → true (field-by-field comparison, not memory address)
type Batch struct {
Tags []string // slices are not comparable
}
x := Batch{Tags: []string{"express"}}
y := Batch{Tags: []string{"express"}}
fmt.Println(x.Tags, y.Tags)
// → [express] [express]
// fmt.Println(x == y)
// → compile error: invalid operation: x == y (struct containing []string cannot be compared)
}
So two Batch values with identical content simply cannot be checked with ==. The escape hatch for tests is reflect.DeepEqual(x, y) — it works through reflection, is slow, and is usually the wrong choice in production code. Better: compare the fields that actually define identity, for example x.ID == y.ID.
⚠ Common mistake:
==comparisons work beautifully — until someone adds a slice or map field to the struct. From that moment every one of those comparison sites fails to compile, often in entirely different files of the package. Keep structs that are compared as values deliberately comparable — or identify them via a single unique field likeIDfrom the start.
Check: When may two values of the same struct type be compared with ==?
Answer: When every field of the struct is comparable — e.g. string, int, or bool; slices and maps forbid the comparison
== compares structs field by field, but only if all field types are comparable. A single slice or map field stops the comparison from compiling at all. reflect.DeepEqual is the fallback for tests — in production code a targeted field comparison is clearer and faster.
Takeaways:
Package{ID: ...} is the Go idiom.var p Package is valid immediately — every field carries its zero value.== compares field by field and only compiles when all fields are comparable.reflect.DeepEqual only in tests; in code, compare key fields like ID.A classic from code review: a team builds account management, the Deposit method compiles, all tests are green — yet the balance never changes. The bug is invisible because it is not an error in the classic sense; it is a question of semantics: value or pointer receiver?
Methods in Go are functions with a receiver as the first parameter: func (a Account) Deposit(amount int) is at its core Deposit(a Account, amount int). And parameters in Go are copied. That single sentence explains almost everything in this lesson.
package main
import "fmt"
type Account struct {
Owner string
Balance int // in cents
}
// Value receiver: Deposit operates on a copy of Account
func (a Account) Deposit(amount int) {
a.Balance += amount // the increase vanishes inside the copy
}
func main() {
acc := Account{Owner: "Mara", Balance: 100}
acc.Deposit(50)
fmt.Println(acc.Balance)
// → 100 — the 50 are silently gone, the compiler does not warn
}
The Receiver Is a Parameter
func (a Account) Deposit(...) passes the struct by value — the method sees a copy. func (a *Account) Deposit(...) passes a pointer — the method works on the original. Make this decision deliberately per type, not per method on a whim.
The rules are best understood semantically rather than memorized:
// Pointer receiver: Deposit changes the original
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
// Value receiver: read-only, the copy is cheap here
func (a Account) Describe() string {
return fmt.Sprintf("%s: %d cents", a.Owner, a.Balance)
}
func main() {
acc := Account{Owner: "Mara", Balance: 100}
acc.Deposit(50) // Go passes &acc automatically because acc is addressable
fmt.Println(acc.Describe())
// → Mara: 150 cents
}
A look ahead: methods with a pointer receiver belong to the method set of *Account, not of Account. Once interfaces enter the picture, that decides whether a value satisfies the contract — which is why you choose consistently from day one.
⚠ Common mistake:
Depositwith a value receiver compiles flawlessly but only increases a copy — the deposit vanishes without any warning. As soon as one method of a type mutates (or the struct is large): pointer receivers for all methods of the type, not just the writing ones.
Check: When is a pointer receiver the right choice?
Answer: When the method should change the caller's state — or the struct is so large that copies cost measurably
The decisive reason is semantics: value receivers work on a copy, so mutations are lost. Performance with large structs and consistent receivers across a type are good secondary reasons — blanket
always pointeris just as wrong asalways value.
Takeaways:
acc.Deposit(50) passes &acc automatically as long as acc is addressable.*Account — that becomes decisive with interfaces later.The team grows: UserService, OrderService, and ShipmentService — all of them need logging. The OO reflex says: common base class, everyone inherits Log. Go has no inheritance, and that is a deliberate design decision. The answer is composition: a type embeds another one (embedding) and gets its fields and methods "promoted" upward (promotion).
Embedding is nothing exotic: a field without a name, whose type name becomes the field name. Everything we learned about structs and methods in the last two lessons still applies — access just gets shorter.
package main
import "fmt"
type Logger struct {
Prefix string
}
func (l Logger) Log(msg string) {
fmt.Printf("[%s] %s\n", l.Prefix, msg)
}
// UserService embeds Logger — the field is simply called Logger
type UserService struct {
Logger
Users map[string]int
}
func main() {
svc := UserService{Logger: Logger{Prefix: "user-svc"}}
svc.Log("started")
// → [user-svc] started
fmt.Println(svc.Prefix)
// → user-svc (promoted: svc.Prefix is svc.Logger.Prefix)
}
Promotion Is Sugar, Not Inheritance
svc.Log("x") is shorthand for svc.Logger.Log("x") — the compiler merely augments the outer struct with the fields and methods of the embedded type. There is no dynamic dispatch and no feedback loop: the embedded Logger knows nothing about its host.
If the outer type defines a method with the same name, it shadows the promoted method — analogous to variable shadowing from Module 2. Nothing changes for the embedded type; whoever wants the original variant calls it explicitly.
type OrderService struct {
Logger
}
// Log shadows Logger's promoted method
func (o OrderService) Log(msg string) {
o.Logger.Log("ORDER: " + msg)
}
func main() {
orders := OrderService{Logger: Logger{Prefix: "order-svc"}}
orders.Log("New order 104")
// → [order-svc] ORDER: New order 104
orders.Logger.Log("direct call still works")
// → [order-svc] direct call still works
}
If that sounds too static to you — exactly, and that is the point: Go favors small, explicit types with clear responsibility ("has a logger") over deep "is a" hierarchies. When you need interchangeable behavior, you reach for interfaces; embedding is pure reuse of structure and methods.
⚠ Common mistake: Embedding is not inheritance: if a method of the embedded type calls a same-named method, the embedded type's version always runs — the "override" on the outer type is never reached. Anyone expecting a dynamic dispatch chain from Java or C# will hunt this bug for a very long time.
Check: UserService embeds Logger and also defines its own Log method. What happens on the call svc.Log(...)?
Answer: The outer type's own Log method runs and shadows the promoted one — the original stays reachable via svc.Logger.Log
The outer method shadows the promoted one — no error, no double call. Anyone expecting dynamic dispatch from inheritance languages is wrong here: the embedded Logger does not know the methods of its host type.
Takeaways:
svc.Log(...) is shorthand for svc.Logger.Log(...) — no dynamic dispatch.Our cache runs smoothly — until a new colleague declares it without knowing our initialization rules: var c Cache, then the first write access, and production is down with panic: assignment to entry in nil map. Go has no constructors in the language core — but it has a convention that prevents exactly this accident: the NewX function.
It is a perfectly ordinary function with two jobs: set sensible defaults and reject invalid states from the start. Because it is a plain function, it can validate parameters and return errors — something constructors in many other languages cannot do.
package main
import (
"errors"
"fmt"
)
type Cache struct {
maxItems int
items map[string]string
}
// NewCache is the idiomatic constructor: set defaults, enforce valid states
func NewCache(maxItems int) (*Cache, error) {
if maxItems < 1 {
return nil, errors.New("maxItems must be greater than 0")
}
return &Cache{
maxItems: maxItems,
items: make(map[string]string),
}, nil
}
func main() {
if _, err := NewCache(-5); err != nil {
fmt.Println("Error:", err)
// → Error: maxItems must be greater than 0
}
c, _ := NewCache(64)
fmt.Println("Cache ready for", c.maxItems, "items")
// → Cache ready for 64 items
}
NewX Instead of Constructors
The standard library shows the pattern everywhere: errors.New, bytes.NewBuffer, time.NewTicker. A NewX function returns a pointer to a fully initialized value — and, as a plain function, can validate parameters and return errors.
Our service keeps gaining knobs: port, timeout, retry limit. A parameterless NewServer() would be too rigid, while NewServer(host, port, timeout, retries) is positionally unreadable — and every extension breaks all existing callers. The idiomatic answer: functional options. Each option is a function that modifies the value under construction; the defaults apply whenever no option is passed.
package main
import (
"fmt"
"time"
)
type Server struct {
host string
port int
timeout time.Duration
}
// Option is a function that modifies the Server during construction
type Option func(*Server)
func WithPort(port int) Option {
return func(s *Server) { s.port = port }
}
func WithTimeout(d time.Duration) Option {
return func(s *Server) { s.timeout = d }
}
// NewServer sets defaults and lets callers deviate selectively
func NewServer(opts ...Option) *Server {
s := &Server{host: "localhost", port: 8080, timeout: 5 * time.Second}
for _, opt := range opts {
opt(s)
}
return s
}
func main() {
srv := NewServer(WithPort(9090), WithTimeout(time.Second))
fmt.Println(srv.host, srv.port, srv.timeout)
// → localhost 9090 1s
}
Staying honest: with two or three parameters, plain arguments or a config struct are more readable and more honest. Functional options pay off only with many freely combinable settings — gRPC clients are the best-known real-world example.
⚠ Common mistake:
var c Cacheinstead ofNewCache:itemsis nil, and the first write access crashes withpanic: assignment to entry in nil map. Exported structs with uninitialized map fields practically invite this. Team convention: types that need initialization get unexported fields and exactly oneNewXfunction — then the compiler keeps everyone on the right path.
Check: When do functional options pay off over a config struct as a parameter?
Answer: When there are many optional parameters with defaults and the list should grow later without breaking existing callers
The real win is additive growth: every new option is a new WithX constructor while the NewServer signature stays stable. With two or three parameters a plain config struct or normal parameters read better — options are a tool, not a dogma.
Takeaways:
NewX functions are Go's constructors: set defaults, validate parameters, return a pointer.NewX prevents that.NewX enforce the valid path at compile time.WithPort(9090)) allow optional parameters without breaking signatures — but only use them when there really are many.Our parcel tracking service goes to production, and the frontend team looks at the interface for the first time. Without any intervention Go serializes field names unchanged: ID becomes ID, WeightKg becomes WeightKg. Go export names are PascalCase, but APIs and configs usually expect snake_case. The JSON tag is the single place where the outward-facing name is defined authoritatively — the struct becomes the contract.
package main
import (
"encoding/json"
"fmt"
)
type Shipment struct {
ID string `json:"id"`
City string `json:"city"`
WeightKg float64 `json:"weight_kg"`
Note string `json:"note,omitempty"` // empty? then not in the JSON at all
Internal string `json:"-"` // internal, never serialized
}
func main() {
s := Shipment{ID: "DE-104", City: "Berlin", WeightKg: 2.4}
data, _ := json.Marshal(s)
fmt.Println(string(data))
// → {"id":"DE-104","city":"Berlin","weight_kg":2.4}
}
Tags Define the Wire to the Outside
omitempty makes zero values disappear entirely — the trick that keeps Note out of the output above. json:"-" removes fields from serialization completely, for internal IDs or cache fields. A field without a tag travels under its Go field name.
For a PATCH endpoint one rule applies: if a field was not sent at all, we must not touch it. An empty string is a legitimate change — omitempty does not help here, because that is pure marshalling logic. The clean answer is pointer fields: nil means "not sent", a set pointer means "change to this value".
type PatchRequest struct {
City *string `json:"city"`
Fragile *bool `json:"fragile"`
}
func main() {
raw := []byte(`{"city":"Hamburg"}`)
var patch PatchRequest
if err := json.Unmarshal(raw, &patch); err != nil {
fmt.Println("Error:", err)
return
}
if patch.City != nil {
fmt.Println("new city:", *patch.City)
// → new city: Hamburg
}
if patch.Fragile == nil {
fmt.Println("Fragile remains unchanged")
// → Fragile remains unchanged
}
}
Two everyday facts to finish: json.Unmarshal matches keys generously — "CITY" also fills the city field. And for readable debug output there is json.MarshalIndent(v, "", " "), while production keeps the compact Marshal.
⚠ Common mistake: You put
omitemptyon atime.Timefield and wonder why the empty date is still serialized: struct values never count as "empty" — only true zero values like0,"",false, andnildisappear. For "sometimes omit the field entirely" you need a pointer such as*time.Time.
That closes Module 6 — from a bare bundle of data to an API-ready data model.
Weekly check: have you mastered the following points?
== compiles for structs — and what slices and maps do to it?NewX from the zero-value trap?omitempty, and pointer fields?Check: What does omitempty in a JSON tag do?
Answer: Fields with a zero value — empty string, 0, false, nil — are omitted during marshalling; struct-like types such as time.Time are not covered
omitempty is pure marshalling: zero values disappear from the output. But an empty time.Time value is a valid struct and therefore never empty — only a pointer field helps here. During unmarshal, omitempty has no effect anyway.
Takeaways:
== compares field by field and requires every field to be comparable — Module 6 in one sentence per lesson: define and compare values cleanly.NewX and functional options keep instantiation valid, extensible, and panic-free.omitempty, json:"-", and pointer fields for genuine optionality.Course navigation: ← Module 5 · All 20 modules · Module 7 →