Structs, Methods, Constructors, Embedding & Struct Tags
"The only way to have dynamically dispatched methods is through an interface. Methods on a struct or any other concrete type are always resolved statically." — The Go FAQ, How do I get dynamic dispatch of methods? (go.dev/doc/faq, read with Go 1.27)
Summary: A struct is a fixed sequence of typed fields; methods attach behaviour to any named type through a value or pointer receiver; embedding composes types by promoting fields and methods without creating a class hierarchy; tags are strings that libraries read through reflect. Focus: Literals (keyed vs positional), comparability, anonymous and empty structs, useful zero values, NewX constructors and functional options, value vs pointer receivers, nil receivers, method sets and addressability, embedding (promotion, shadowing, ambiguous selectors, embedded interfaces and pointers, the sync.Mutex trap), struct tags and reflect.StructTag, padding and fieldalignment, copying, equality, immutability, and generic structs. Learning goal: Model a domain type in Go the way the standard library does: decide value or pointer receiver from rules, write constructors that cannot return half-built values, compose with embedding without expecting inheritance, and predict every compiler, vet and runtime error this page lists.
This page owns the struct type and everything attached to it. It does not re-teach its neighbours: what a pointer is, escape analysis and the stack/heap split live in Pointers & Memory Model Basics; interfaces, type assertions and type switches in Interfaces, Type Assertions, Type Switches & any; the full encoding/json behaviour (decoders, RawMessage, custom marshalers) in JSON, XML, Struct Tags, Encoder/Decoder, Base64; walking types at run time in reflect: When and How; type parameters and constraints in Generics; sync.Mutex itself in sync & atomic; and slices in Arrays, Slices & Maps. The design side (entities vs value objects) is in Entities & Value Objects and composition in Composing Objects & the Law of Demeter.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has structs and methods but no classes | Why it exists |
| Spec, Effective Go, FAQ, version history | Where it comes from |
| Declaring structs, field rules, recursive types | Struct types |
T{a, b} vs T{A: a}, vet's composite check | Struct literals |
==, map keys, "cannot be compared" | Comparability |
struct{...}{...} in tests, struct{} sets | Anonymous and empty structs |
| Types that work without a constructor | Zero value usability |
NewX, validation, pointer or value | Constructors |
WithTimeout(...) style APIs | Functional options |
func (c *Counter) vs func (c Counter) | Receivers |
| Methods that work on a nil pointer | Nil receivers |
| "method String has pointer receiver" | Method sets |
| "cannot call pointer method on ..." | Addressability |
p.Add and Point.Add as values | Method values and expressions |
| Promoted fields and methods | Embedding |
| Name conflicts, "ambiguous selector" | Shadowing |
| Why "overriding" does not work | No virtual dispatch |
| Decorators with an embedded interface | Embedded interfaces |
*log.Logger inside a struct, nil panics | Embedded pointers |
Embedding sync.Mutex, "passes lock by value" | Mutex embedding |
json:"...", db:"...", reflect.StructTag | Struct tags |
Lower-case fields and JSON, Unmarshal(non-pointer ...) | Unexported fields |
Padding, unsafe.Sizeof, fieldalignment | Field alignment |
Range copies, []T vs []*T | Copying and slices of structs |
Owner() not GetOwner(), String() | Getters, setters and Stringer |
reflect.DeepEqual, cmp.Equal | Comparing structs |
| Value objects that cannot change | Immutability |
Page[T], pointer-method constraints, Go 1.27 generic methods | Generics with structs |
| Exact compiler, vet and runtime messages | Mechanics |
| Fixes with runnable code | Solving the classic problems |
| Which option for which situation | Choosing |
| Classes, traits, readonly properties | For PHP/Laravel developers |
| Monolith to distributed system | In architecture |
| Reproduce everything | Lab |
Everything in one minute
The building blocks. Each row is unpacked in the concept catalogue.
| Thing | In plain words | Tiny example | Trap |
|---|---|---|---|
| Struct | Named, typed fields in a fixed order | type User struct { ID int64; Email string } | Field order changes size (padding) |
| Keyed literal | Fields by name, any order, rest zero | User{Email: "a@example.com"} | None; the default for types you do not own |
| Positional literal | Every field, in order | Point{1, 2} | Breaks when a field is added; vet flags imported types |
| Zero value | Every field at its zero | var buf bytes.Buffer is ready | A nil map field panics on write |
| Constructor | A NewX function that validates | NewClient(url, WithTimeout(d)) | Returning a half-built value without an error |
| Method | A function with a receiver | func (m Money) String() string | Receiver is a copy unless it is a pointer |
| Pointer receiver | Method can mutate, no copy | func (c *Counter) Inc() | Value Counter no longer satisfies interfaces needing Inc |
| Embedding | A field whose type name is its name; selectors promoted | type Dog struct { Animal } | It is not inheritance |
| Struct tag | A string literal after a field | `json:"id" db:"id"` | Typos are silent unless go vet runs |
Value or pointer: the rules in one table.
| Situation | Receiver | Why |
|---|---|---|
| Method mutates the receiver | *T | A value receiver mutates a copy |
Struct contains sync.Mutex, sync.WaitGroup, atomics | *T | Copying a lock breaks it; vet copylocks |
| Large struct | *T | Copy cost equals passing every field as an argument |
Any other method of T uses *T | *T | Keep the method set uniform |
Small immutable value (time.Time, Money, Point) | T | Cheap copy, safe to share, works on values and pointers |
| Map, func or chan type | T | Already a reference; a pointer adds nothing |
| In doubt | *T | CodeReviewComments: "when in doubt, use a pointer receiver" |
Errors you will meet. Exact texts are from Go 1.27.4 (see Mechanics).
| Message | Cause |
|---|---|
ambiguous selector c.Close | Two embedded types promote Close at the same depth |
Counter does not implement fmt.Stringer (method String has pointer receiver) | A value was assigned where *Counter's method set is needed |
cannot call pointer method Inc on Counter | m["a"].Inc() on a map element (not addressable) |
invalid operation: a == b (struct containing []string cannot be compared) | A slice, map or func field |
too few values in struct literal of type P | Positional literal missing fields |
struct literal uses unkeyed fields (vet) | Positional literal of an imported struct |
passes lock by value (vet) | Value receiver on a struct with a mutex |
panic: runtime error: invalid memory address or nil pointer dereference | Nil embedded pointer or nil embedded interface |
Why it exists
Programs need to group data that belongs together (an order has an ID, lines and a status) and to attach behaviour to that data. Class-based languages bundle three ideas into one construct: the data layout, the behaviour, and a subtype hierarchy with virtual dispatch. Go separates them. A struct is only the layout. Methods can be declared on any named type in the same package, not only structs. Subtyping comes from interfaces, which a type satisfies implicitly. Reuse comes from embedding, which is plain composition with a shortcut for selectors. Each piece is simpler, and the cost is that patterns built on inheritance (template methods, protected hooks, super calls) must be rewritten with interfaces and explicit forwarding.
| Class-based (PHP, Java) | Go |
|---|---|
| A class owns data, methods and its place in a hierarchy | A struct owns data; methods are declared next to it; interfaces give polymorphism |
extends gives subtyping and code reuse together | Embedding gives reuse; interfaces give substitutability; they are separate decisions |
Methods are virtual by default ($this->hook() calls the subclass) | Calls on concrete types are static; only interface calls dispatch dynamically |
Constructors are special (__construct) | Constructors are ordinary functions named NewX by convention |
| Objects are references; assignment shares | Structs are values; assignment copies every field |
Visibility: public/protected/private per member | Visibility per package: upper-case exported, lower-case unexported |
| Annotations/attributes are a language feature | Tags are strings; meaning is whatever a library parses |
The analogy we reuse on this page: a shipping container and its paperwork. A struct is a container with fixed compartments (fields) in a fixed order; small compartments between large ones leave gaps (padding). Copying a struct is shipping an identical container: changes inside the copy never reach the original, unless a compartment holds an address (a pointer) to something outside. A method with a value receiver works on a photocopy of the container; a pointer receiver walks into the original. Embedding is placing a smaller container inside a larger one and painting the inner one's labels on the outside door, so you can reach its compartments directly; the inner container does not know it was packed. Tags are the customs stickers on each compartment: the container does not read them, the customs office (encoding/json, a SQL mapper, a validator) does.
Three common misunderstandings, up front
- "Embedding is inheritance." The embedded value is an ordinary field. Its promoted methods run with the inner value as receiver, so a method of the inner type that calls another method always calls the inner one, never the outer "override". See No virtual dispatch.
- "Use a pointer receiver for speed, a value receiver for safety, and mix as needed." Receiver choice is semantic first (mutation, locks, identity) and changes which types satisfy which interfaces. Mixing receivers makes
Tand*Tsatisfy different interfaces; CodeReviewComments says "Don't mix receiver types." - "A constructor is required." The idiom is the opposite: design types whose zero value is ready (
var mu sync.Mutex,var b bytes.Buffer) and addNewXonly when an invariant needs validation or a dependency must be supplied.
Where it comes from
The specification. The Go spec (read as "Language version go1.27 (May 26, 2026)") defines a struct as "a sequence of named elements, called fields, each of which has a name and a type", calls "a field declared with a type but no explicit field name" an embedded field, and says a field or method of an embedded field "is called promoted if x.f is a legal selector that denotes that field or method f." It defines tags too: "The tags are made visible through a reflection interface and take part in type identity for structs but are otherwise ignored." Method sets: "The method set of a pointer to a defined type T (where T is neither a pointer nor an interface) is the set of all methods declared with receiver *T or T."
Effective Go sets the idioms. On zero values: "the zero value of each type can be used without further initialization." On getters: "it's neither idiomatic nor necessary to put Get into the getter's name." On embedding: "There's an important way in which embedding differs from subclassing. When we embed a type, the methods of that type become methods of the outer type, but when they are invoked the receiver of the method is the inner type, not the outer one." On automatic addressing: "When the value is addressable, the language takes care of the common case of invoking a pointer method on a value by inserting the address operator automatically."
The FAQ explains the design. "Why is there no type inheritance?" answers that "in Go a type automatically satisfies any interface that specifies a subset of its methods." "Why do T and *T have different method sets?" answers that "if an interface value contains a value T, there is no safe way for a method call to obtain a pointer."
The Go Wiki's CodeReviewComments ("Receiver Type") gives the receiver rules this page uses, ending with "Finally, when in doubt, use a pointer receiver."
Functional options come from Rob Pike's January 2014 post "Self-referential functions and the design of options" and were popularised by Dave Cheney's dotGo 2014 talk "Functional options for friendly APIs" ("Functional options let you write APIs that can grow over time.").
Version timeline relevant to structs.
| Version | Change | Where read |
|---|---|---|
| Go 1.1 | encoding/json marshals embedded (anonymous) struct fields | encoding/json source comment: "Handling of anonymous struct fields is new in Go 1.1." |
| Go 1.20 | Spec defines struct comparison "one field at a time ... stopping at the first mismatch" | Go 1.20 release notes |
| Go 1.22 | Each loop iteration gets new variables (affects &v in for _, v := range structs) | Go 1.22 release blog |
| Go 1.24 | json:",omitzero"; testing.B.Loop | Go 1.24 release notes |
| Go 1.26 | new(expr): Age: new(yearsSince(born)) for optional pointer fields; reflect.Type.Fields iterators | Go 1.26 release notes |
| Go 1.27 | Generic methods; "A key in a struct literal may now be any valid field selector", so promoted fields can be keys | Go 1.27 release notes |
The snippets on this page use go 1.24 in go.mod, so the Go 1.26 and 1.27 features are shown separately and the 1.24 module proves they are gated: the type checker reports use of promoted field Base.ID in struct literal of type User requires go1.27 or later.
The concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a precise definition, a sequence, real scenarios, per-situation behaviour, and the fix in Go (full code in Solving the classic problems).
Struct types and fields Must-know
In plain words: a struct type lists fields, each with a name and a type. Upper-case field names are visible outside the package; lower-case ones are not. A struct is a value: assigning it copies all fields.
Common misunderstanding: "A struct variable is a reference, like a PHP object." b := a copies the whole struct; changing b.Name leaves a.Name alone. Only pointer, slice, map, channel, func and interface fields share what they point to.
Definition: StructType = "struct" "{" { FieldDecl ";" } "}", where a field declaration is either a list of names with a type or an embedded type name, optionally followed by a tag. Non-blank field names must be unique; the blank field _ can be used for explicit padding. A struct may not contain itself directly (invalid recursive type: Node refers to itself) but may contain a pointer, slice or map of itself.
1 type Node struct { Val int; Next Node } -> invalid recursive type: Node refers to itself
2 type Node struct { Val int; Next *Node } -> fine: a pointer has a fixed size
3 a := Address{City: "Berlin"}
4 b := a -> copies Street, City, Country
5 b.City = "Paris" -> a.City is still "Berlin"Real scenario: a Customer struct passed by value to a function that "normalises" the email: the caller never sees the normalised email. A linked list or tree that does not compile until the self-reference becomes a pointer. A struct with a Tags []string field: copies share the same backing array, so appending through one copy may or may not be visible through the other.
| Field kind | Copied by b := a | Shared after copy |
|---|---|---|
int, string, bool, arrays, nested structs | Full value | Nothing |
Pointer *T | The address | The pointee |
| Slice | Header (pointer, len, cap) | The backing array |
| Map, chan, func | The reference | The map/channel/function |
| Interface | Type and data word | The dynamic value if it is a pointer |
Fix / how to use it: declare the struct, keep fields unexported when invariants matter, and decide copy semantics consciously; see Copying and slices of structs. Code: literals/literals.go in Solutions.
Struct literals: keyed vs positional Must-know
In plain words: a composite literal builds a struct value inline. A keyed literal names the fields (Address{City: "Berlin"}); a positional literal lists every field in order (Address{"Main St 1", "Berlin", "DE"}).
Common misunderstanding: "Positional literals are just shorter." They are fragile: adding a field to the type breaks every positional literal (too few values in struct literal of type P), and reordering two fields of the same type silently swaps values. You also cannot mix the styles: mixture of field:value and value elements in struct literal.
Definition: for a keyed literal "every element must have a key", omitted fields get their zero value, and duplicates are an error. For a positional literal "the element list must contain an element for each struct field in the order in which the fields are declared." &T{...} allocates a new value each time it is evaluated; Effective Go: "The expressions new(File) and &File{} are equivalent." The composite vet analyzer reports "composite literals of struct types imported from another package that do not use the field-keyed syntax" with the message net.DNSConfigError struct literal uses unkeyed fields. In Go 1.27 a key may be a promoted field (User{ID: 1} when ID comes from an embedded Base), unless the module's go line is older.
1 v1 of package geo: type Address struct { Street, City, Country string }
2 your code: geo.Address{"Main St 1", "Berlin", "DE"} -> compiles; vet warns
3 v2 adds a field: type Address struct { Street, City, Postcode, Country string }
4 your code: too few values in struct literal of type geo.Address
5 keyed literal: geo.Address{Street: "Main St 1", City: "Berlin", Country: "DE"} -> still compilesReal scenario: a dependency upgrade that adds an unexported field to an error struct and breaks every caller that wrote &pkg.Err{err}. A test table of Point{1, 2} values where positional is clearer and safe because the type is local. An Options{} literal in a config loader where keyed fields document intent.
| Literal | Use for | Avoid for |
|---|---|---|
T{A: 1, B: 2} keyed | Everything you do not own; structs with more than 3 fields | Nothing |
T{1, 2} positional | Small local types: points, pairs, test tables of your own types | Imported types (vet), structs that grow |
T{} | Zero value | When an invariant needs a constructor |
&T{...} | A pointer to a fresh value | Nothing; it is the idiomatic new |
Fix / how to use it: keyed by default; run go vet (it runs the composite check, and go test runs a subset of vet automatically). Code: Solutions.
Comparability and == Must-know
In plain words: two structs can be compared with == only if every field type is comparable. Then == compares fields in order. Comparable structs can be map keys.
Common misunderstanding: "== on structs compares what pointers point to." It compares pointer fields by address. And "a struct with a slice can be compared if the slices are equal": it does not compile.
Definition: "Struct types are comparable if all their field types are comparable." Since Go 1.20 the spec says comparison goes "one field at a time, considering fields in the order they appear in the struct type definition, and stopping at the first mismatch." Slices, maps and funcs are not comparable; a struct containing one is not either: invalid operation: a == b (struct containing []string cannot be compared) and, as a map key, invalid map key type Order. Comparing a struct that contains an interface field compiles but panics at run time if the dynamic values are not comparable.
1 type Address struct { Street, City, Country string } comparable
2 seen := map[Address]struct{}{} fine as a key
3 type Order struct { ID int; Lines []string } not comparable
4 a == b compile error
5 type Key struct { V any }; Key{[]int{1}} == Key{[]int{1}} panic: runtime error: comparing uncomparable type []intReal scenario: deduplicating addresses in an import job with map[Address]struct{}. A cache keyed by struct{ TenantID, UserID int64 } instead of a concatenated string. A test that compares two Event values holding time.Time with == and fails intermittently (see Comparing structs).
| Field types | == | Map key | Use instead |
|---|---|---|---|
| Basic types, arrays, comparable structs, pointers, channels | Yes | Yes | |
| Interface fields | Compiles; panics if dynamic type is not comparable | Same risk | Avoid in keys |
| Slice, map, func fields | Compile error | Compile error | slices.Equal, an Equal method, reflect.DeepEqual in tests |
time.Time fields | Compiles but compares monotonic reading and location pointer | Works but surprising | t.Equal(u); strip with Round(0) |
Fix / how to use it: keep key structs small and comparable; write an Equal method when semantic equality differs from field equality. Code: equality in Solutions.
Anonymous structs and the empty struct Good to know
In plain words: you can use a struct type without naming it: struct{ Name string; Want bool }{"x", true}. The empty struct struct{} has no fields and takes zero bytes.
Common misunderstanding: "Two anonymous structs with the same fields are different types." They are identical types when field names, types, order and tags match, so one is assignable to the other. Tags count: a different tag makes a different type.
Definition: an anonymous struct is a struct type literal used directly in a declaration. struct{} has size 0; map[K]struct{} is the idiomatic set and chan struct{} the idiomatic signal. A zero-size field at the end of a struct still gets padding so its address does not point past the struct (measured: struct{ N int64; End struct{} } is 16 bytes).
Real scenario: table-driven tests ([]struct{ name string; in Address; want bool }); one-off JSON shapes in a handler (var req struct{ Email string `json:"email"` }); a done chan struct{}; a set of seen IDs.
Fix / how to use it: anonymous structs for test tables and single-use request/response shapes; a named type as soon as two functions share it. Code: TestCase in literals.
Zero value usability Must-know
In plain words: every struct starts with all fields at their zero value. Good Go types are designed so that this zero value already works.
Common misunderstanding: "Every type needs NewX." sync.Mutex, bytes.Buffer, strings.Builder and http.Client work at their zero value. And the reverse: "zero value is always safe": a nil map field panics on write (panic: assignment to entry in nil map), and a nil embedded pointer panics on use.
Definition: Effective Go: "it's helpful to arrange when designing your data structures that the zero value of each type can be used without further initialization", and "The zero-value-is-useful property works transitively": a struct of a sync.Mutex and a bytes.Buffer is ready too. Lazy initialisation (if c.items == nil { c.items = make(...) }) inside pointer methods keeps a map field zero-safe. A nil func field can mean "use the default".
1 var l AuditLog mu: unlocked mutex, buf: empty buffer, now: nil
2 l.Record("login") now == nil -> time.Now; buf grows
3 var c Cache items: nil map
4 c.Set("k", "v") Set sees nil, makes the map, then writes
5 var bad struct{ m map[string]int }; bad.m["x"] = 1 panic: assignment to entry in nil mapReal scenario: a Cache embedded as a field in a service struct that nobody initialises; a metrics registry declared as a package variable; a test that declares var s Service and expects it to work.
Fix / how to use it: zero-safe fields (mutexes, buffers, lazily made maps, nil func meaning default); document "The zero value is ready to use" in the type's comment. Code: AuditLog in literals, Cache in mutexembed.
Constructors: NewX Must-know
In plain words: Go has no constructor keyword. A constructor is a function, by convention NewX (or New when the package exports one main type), that builds a valid value and returns it, usually with an error.
Common misunderstanding: "NewX must return a pointer." Return a pointer for large or stateful types with pointer receivers (*Client, *Server); return a value for small value types (time.Date returns time.Time, NewMoney returns Money). Another one: "a constructor guarantees validity." Only if the fields are unexported; otherwise anyone can write Money{cents: -1} in the same package or Money{} anywhere.
Definition: a function in the same package that sets defaults, applies arguments, validates invariants and returns (T, error) or (*T, error). Effective Go's NewFile returns &File{fd: fd, name: name}; returning the address of a local is safe because "the storage associated with the variable survives after the function returns." The zero value remains reachable (var m Money), so methods must handle it or the type must document that it is invalid.
1 NewMoney(1999, "EUR") -> Money{cents:1999, currency:"EUR"}, nil
2 NewMoney(1, "euro") -> Money{}, error wrapping ErrCurrency
3 NewClient("") -> nil, "NewClient: baseURL is required"
4 NewClient(url) -> defaults: timeout 5s, retries 2, slog.Default()
5 caller never holds a *Client that failed validationReal scenario: a Money type that must never have an empty currency; an HTTP client wrapper whose timeout must be positive; a repository that needs a *sql.DB and refuses nil; a domain entity whose ID must be a valid UUID.
| Return | When | Standard library example |
|---|---|---|
T | Small, immutable, value receivers | time.Date, netip.AddrFrom4 |
(T, error) | Value type with validation | netip.ParseAddr, url.Parse returns *URL instead |
*T | Stateful, pointer receivers, never fails | bytes.NewBuffer, bufio.NewReader |
(*T, error) | Stateful with validation or I/O | os.Open, sql.Open |
MustX that panics | Package-level init with constant input | regexp.MustCompile, template.Must |
Fix / how to use it: unexported fields plus NewX for types with invariants; exported fields and no constructor for plain data. Code: constructors in Solutions.
Functional options and config structs Important
In plain words: when a constructor has many optional settings, either pass a Config struct whose zero fields mean "default", or pass variadic Option functions such as WithTimeout(2*time.Second).
Common misunderstanding: "Functional options are always better." They cost a closure per option, are harder to load from a file or environment, and hide the available settings across many functions. A config struct is simpler when settings come from configuration.
Definition: Pike's pattern: "First, we define an option type. It is a function that takes one argument, the Foo we are operating on." The constructor sets defaults, then applies each option in order; options may validate and return an error. A config struct uses zero as default; when zero is a valid explicit value (retries = 0), use a pointer field (Retries *int) or a separate set flag.
1 NewClient(url) timeout 5s, retries 2
2 NewClient(url, WithTimeout(time.Second)) timeout 1s, retries 2
3 NewClient(url, WithRetries(0)) retries 0 (explicit zero is expressible)
4 NewClient(url, WithTimeout(-1)) nil, "NewClient: timeout must be positive, got -1ns"
5 NewClientFromConfig(Config{BaseURL: url}) same defaults; Retries nil means 2Real scenario: grpc.NewClient(target, grpc.WithTransportCredentials(...)) and many SDKs use options; http.Server{Addr: ..., ReadHeaderTimeout: ...} uses a config struct; a library that started with three parameters and needs a tenth.
| Style | Strength | Weakness |
|---|---|---|
| Many positional parameters | Explicit | Breaks callers when a parameter is added |
| Config struct | One place to see all settings; easy to load from YAML/env | Zero vs unset ambiguity |
| Functional options | Grows without breaking callers; options can validate | More code; settings spread over functions |
| Builder with chained setters | Familiar from PHP/Java | Mutable intermediate state; errors only at Build() |
Fix / how to use it: options for libraries with stable defaults, config structs for application wiring; both can coexist (NewClientFromConfig maps onto options). Code: Solutions.
Methods and receivers: value vs pointer Must-know
In plain words: a method is a function with a receiver parameter written before the name. A value receiver gets a copy; a pointer receiver gets the address and can change the original.
Common misunderstanding: "c.IncValue() on a variable changes c." It changes a copy that is thrown away; nothing warns you. The FAQ: "valueMethod is called with a copy of the caller's argument (that's the definition of passing a value), so changes it makes will be invisible to the caller."
Definition: "the receiver ... behaves exactly as if it were an argument to the method" (FAQ). The receiver base type must be a defined type declared in the same package, and not a pointer or interface type. Methods can be declared on any such type: type Status int can have String(). CodeReviewComments: use a pointer if the method mutates, if the struct contains a sync.Mutex, if it is large; use a value for "small unchanging structs"; "Don't mix receiver types"; "when in doubt, use a pointer receiver." Receiver names are short and consistent (c for Client), never this or self.
1 c := Counter{name: "hits"} n = 0
2 c.IncValue() copy.n = 1, copy discarded; c.n = 0
3 c.Inc() compiler: (&c).Inc(); c.n = 1
4 p := Point{1, 2}; q := p.Add(Point{1, 1}) p unchanged, q = (2,3)Real scenario: a counter, a state machine, a cart: pointer receivers. time.Time, a Money amount, a 2D point, an enum: value receivers. A struct used both ways: Sum() on value, Add() on pointer, and suddenly Cart no longer satisfies an interface that a *Cart does.
| Receiver | Copies | Mutation visible to caller | Callable on value variable | Callable on pointer | In method set of T |
|---|---|---|---|---|---|
func (t T) M() | Whole struct | No | Yes | Yes (auto *p) | Yes |
func (t *T) M() | Pointer (8 bytes) | Yes | Only if addressable (auto &v) | Yes | No, only *T |
Fix / how to use it: pick per type, not per method, using the decision diagram. Code: receivers in Solutions.
Nil receivers Important
In plain words: calling a pointer method on a nil pointer is legal; the method runs with t == nil. It panics only if the method touches a field.
Common misunderstanding: "var t *Tree; t.Sum() always panics." It panics only when Sum dereferences t. Designing for nil (empty tree, no-op logger) is idiomatic.
Definition: a method call x.M() with a pointer receiver passes x as is; no dereference happens before the call. A field access through nil panics: panic: runtime error: invalid memory address or nil pointer dereference followed by [signal SIGSEGV: segmentation violation ...]. Value-receiver methods called through a nil pointer panic immediately, because the call must copy *p.
1 var root *Tree nil
2 root.Sum() Sum sees t == nil, returns 0
3 root = root.Insert(5) Insert sees nil, returns &Tree{Val: 5}
4 var l *Logger; l.Log("x") Log reads l.prefix -> nil pointer dereferenceReal scenario: a recursive tree or linked list; an optional *Metrics that is nil in tests and whose methods are no-ops; protobuf-style getters that return a zero value on nil messages.
Fix / how to use it: check if t == nil first in methods that should accept nil; otherwise let construction guarantee non-nil. Code: Tree in receivers.
Method sets and interface satisfaction Must-know
In plain words: the method set of T holds its value-receiver methods; the method set of *T holds both value and pointer methods. A type satisfies an interface when the interface's methods are in its method set.
Common misunderstanding: "If I can call c.String() on a variable, c is a fmt.Stringer." Calling works on an addressable variable because the compiler inserts &; interface satisfaction has no such rewrite. var s fmt.Stringer = c fails with Counter does not implement fmt.Stringer (method String has pointer receiver), and fmt.Println(c) silently prints {hits 3} instead of hits=3.
Definition: spec: "The method set of a defined type T consists of all methods declared with receiver type T", and the set of *T "is the set of all methods declared with receiver *T or T." FAQ: "if an interface value contains a value T, there is no safe way for a method call to obtain a pointer." Embedding adds promoted methods by the rules in Embedding. A compile-time assertion var _ fmt.Stringer = (*Counter)(nil) fails the build when a method set changes.
1 func (c *Counter) String() string
2 fmt.Println(&c) *Counter is a Stringer -> "hits=3"
3 fmt.Println(c) Counter is not -> "{hits 3}" (no error!)
4 var s fmt.Stringer = c compile error: method String has pointer receiver
5 var _ fmt.Stringer = (*Counter)(nil) build-time check, zero costReal scenario: an http.Handler implemented with a pointer receiver and registered as a value; a json.Marshaler with a pointer receiver that is ignored when a value is marshalled; a sort.Interface on a value type whose Swap needs a pointer.
Fix / how to use it: assign &v to interfaces when methods use pointer receivers; add var _ I = (*T)(nil) next to the type. Code: receivers in Solutions.
Addressability and the automatic & Important
In plain words: Go lets you write c.Inc() for a variable c even though Inc needs *Counter, by taking the address for you. This auto address only works on things that have a stable address.
Common misunderstanding: "m["a"].Inc() works like s[0].Inc()." Map elements are not addressable (the map may move them when it grows): cannot call pointer method Inc on Counter, and assigning a field fails with cannot assign to struct field m["a"].n in map.
Definition: addressable operands are "a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array" (spec, Address operators). Composite literals are an exception: &T{} is allowed though T{} is not addressable. For a pointer method M, x.M() is shorthand for (&x).M() when x is addressable; for a value method, p.M() is shorthand for (*p).M().
1 cs := []Counter{{}, {}}; cs[0].Inc() slice element: addressable -> (&cs[0]).Inc()
2 m := map[string]Counter{}; m["a"].Inc() cannot call pointer method Inc on Counter
3 v := m["a"]; v.Inc(); m["a"] = v copy out, mutate, write back
4 mp := map[string]*Counter{}; mp["a"].Inc() map of pointers: fine
5 NewCounter().Inc() fine if NewCounter returns *Counter; not if it returns CounterReal scenario: a map of sessions keyed by ID whose Touch() method needs a pointer; a function returning a struct value on which a pointer method is chained; iterating for _, v := range and calling a mutating method on v.
| Expression | Addressable | x.PtrMethod() |
|---|---|---|
Variable v | Yes | Yes |
*p | Yes | Yes |
s[i] (slice) | Yes | Yes |
a[i] (array variable) | Yes | Yes |
v.f (field of addressable struct) | Yes | Yes |
m[k] (map element) | No | Compile error |
f() (function result) | No | Compile error |
T{} (composite literal) | No (but &T{} is allowed) | Compile error |
| Value inside an interface | No | Not in method set |
Fix / how to use it: map[K]*T when values are mutated in place, or copy out and write back; use the index form for i := range s { s[i].Inc() }. Code: IncAll in receivers.
Method values and method expressions Good to know
In plain words: p.Add (no call) is a function with p already bound; Point.Add is a function whose first parameter is the receiver.
Common misunderstanding: "A method value tracks later changes to the receiver." For a value receiver, the receiver is copied when the method value is evaluated; for a pointer receiver, the pointer is copied, so changes through it are visible.
Definition: method value x.M evaluates x and saves a copy of it; method expression T.M yields func(T, args...), and (*T).M yields func(*T, args...).
Real scenario: passing srv.handleOrders as an http.HandlerFunc; defer mu.Unlock wrapped in helpers; slices.SortFunc(xs, Item.Compare).
Fix / how to use it: prefer method values for callbacks; remember that defer x.M() evaluates x at the defer line. Code: Joined in receivers.
Embedding: promoted fields and methods Must-know
In plain words: writing a type name without a field name inside a struct embeds it. The embedded value is a real field named after its type, and its fields and methods can be used as if they belonged to the outer struct.
Common misunderstanding: "The outer type is now an Animal." A Dog cannot be passed where an Animal is expected; there is no subtype relation between structs. Only interfaces relate types: Dog satisfies any interface whose methods are in its method set, including promoted ones.
Definition: "A field declared with a type but no explicit field name is called an embedded field." It is T or *T where T is a type name, not a pointer type or type parameter; "the unqualified type name acts as the field name" (P.T3 gives field T3). Method set rules for S embedding T: "the method sets of S and *S both include promoted methods with receiver T. The method set of *S also includes promoted methods with receiver *T." For S embedding *T: both S and *S include methods with receiver T or *T. Before Go 1.27 a promoted field cannot be a key in a struct literal; you write User{Base: Base{ID: 1}}.
1 type Dog struct { Animal; Timestamps }
2 d.Name == d.Animal.Name promoted field
3 d.Touch(now) == (&d.Timestamps).Touch(now) promoted *Timestamps method, d addressable
4 Dog{Name: "Rex"} go1.24: requires go1.27 or later ; write Dog{Animal: Animal{Name: "Rex"}}
5 var a Animal = d cannot use d (variable of struct type Dog) as Animal value in variable declarationReal scenario: a Timestamps or AuditFields struct embedded in every entity; bufio.ReadWriter embedding *Reader and *Writer; a handler embedding http.ResponseWriter to intercept WriteHeader; a test fake embedding the interface it fakes.
S embeds | Method set of S gets | Method set of *S gets | Zero value of the field |
|---|---|---|---|
T | T's value methods | T and *T methods | Zero T, usable |
*T | T and *T methods | T and *T methods | nil; field access panics |
Interface I | I's methods | I's methods | nil; any call panics |
Fix / how to use it: embed for genuine "has-a with the same API" cases; use a named field when you want to hide the inner API. Code: embedding in Go.
Shadowing and ambiguous selectors Important
In plain words: if the outer struct declares a field or method with the same name as a promoted one, the outer one wins. If two embedded types promote the same name at the same depth, using that name is a compile error.
Common misunderstanding: "Embedding two types with the same method fails to compile." It compiles; only using the ambiguous name fails. Effective Go: "if the duplicate name is never mentioned in the program outside the type definition, it is OK." This is why a dependency adding a method can break your code far away.
Definition: for a selector x.f, the compiler looks for f at depth 0 (declared on x's type), then depth 1 (in embedded fields), and so on; "a field or method X hides any other item X in a more deeply nested part of the type." If the shallowest depth has more than one f, the selector is illegal: ambiguous selector c.Close. You can still reach each one explicitly: c.A.Close(), c.B.Close().
1 type C struct { A; B } A.Close and B.Close both at depth 1
2 var c C compiles
3 c.Close() ambiguous selector c.Close
4 c.A.Close() fine: explicit path
5 func (C) Close() error depth 0 shadows both; c.Close() now calls C.CloseReal scenario: a struct embedding both *bufio.Reader and *bufio.Writer that need not conflict; a service embedding two clients that both gain a Close method in a minor release; encoding/json silently dropping two same-depth fields with the same JSON name ("Otherwise there are multiple fields, and all are ignored; no error occurs.").
Fix / how to use it: declare the method on the outer type to resolve the conflict deliberately (for Close, close both); prefer named fields when two embedded types overlap. Code: compileerrs in Solutions.
Not inheritance: no virtual dispatch Must-know
In plain words: a promoted method runs on the inner value. When Animal.Describe calls a.Sound(), it calls Animal.Sound, even if the outer Dog declares its own Sound.
Common misunderstanding: "Declaring Dog.Sound overrides it for Describe." That is how PHP and Java work ($this->sound() dispatches on the runtime class). In Go "Methods on a struct or any other concrete type are always resolved statically"; the inner value has no pointer back to the outer one.
Definition: d.Describe() is shorthand for d.Animal.Describe(); inside, the receiver is the Animal copy. Effective Go: "when they are invoked the receiver of the method is the inner type, not the outer one." Dynamic dispatch exists only through interface values.
1 d := Dog{Animal: Animal{Name: "Rex"}}
2 d.Sound() Dog.Sound -> "woof"
3 d.Describe() Animal.Describe(d.Animal) -> calls Animal.Sound -> "Rex says ..."
4 DescribeAny(d.Name, d) Speaker interface holds Dog -> Dog.Sound -> "Rex says woof"Real scenario: a port of a PHP abstract class with a template method (process() calls $this->validate()) that silently stops calling the "child" validation; a base repository whose Save calls r.table() expecting the embedding type's table name; a base HTTP handler whose ServeHTTP calls h.authorize().
| PHP/Java idiom | Go replacement |
|---|---|
| Abstract class with template method | Function or struct that takes an interface for the varying step |
protected hook overridden by subclass | Field of func type or interface, set by the constructor |
parent::method() | Explicit call o.Inner.Method() |
Subtype polymorphism (Animal $a) | Interface parameter (Speaker) |
Fix / how to use it: pass the varying behaviour as an interface or func field. Code: DescribeAny in Go.
Embedded interfaces and decoration Important
In plain words: a struct can embed an interface type. All the interface's methods are promoted and forward to whatever value the field holds, so you override only the methods you care about. This is the cheapest decorator in Go.
Common misunderstanding: "If I forget to set the embedded interface, the missing methods do nothing." They panic with a nil pointer dereference, because the field is a nil interface. Also: "embedding a big interface in a test fake is safe." It compiles even when you implement only one method; calling another panics at run time, far from the cause.
Definition: an embedded interface field Store makes Store's methods part of the struct's method set (for both S and *S). A method declared on the outer struct shadows the promoted one; inside it, call c.Store.Get(...) to forward.
1 cs := &CountingStore{Store: MapStore{}}
2 s.Put(ctx, "k", "v") promoted -> MapStore.Put
3 s.Get(ctx, "k") CountingStore.Get: gets++, then c.Store.Get
4 var zero CountingStore; zero.Put(...) Store is nil -> nil pointer dereferenceReal scenario: metrics or logging around a repository; a ResponseWriter wrapper that records the status code; a read-only Store that overrides Put and Delete to return an error; a test fake embedding pb.UnimplementedXServer-style types.
Fix / how to use it: require the inner value in the constructor; in tests, embed the interface only when calling an unimplemented method should panic loudly. Code: CountingStore in Go.
Embedded pointers Important
In plain words: embedding *T instead of T shares one inner value between several outer values and promotes both value and pointer methods, but the zero outer value has a nil pointer.
Common misunderstanding: "var j Job is usable like any zero value." Its *Logger is nil; j.Printf(...) panics inside Logger.Printf when it touches a field.
Definition: for S containing *T, "the method sets of S and *S both include promoted methods with receiver T or *T." Selectors through the pointer dereference it implicitly. Struct literal keys must not traverse embedded pointer fields.
Real scenario: Effective Go's Job embedding *log.Logger; bufio.ReadWriter embedding *Reader and *Writer; several handlers sharing one embedded *Deps.
Fix / how to use it: embed a pointer only with a constructor that sets it (NewJob), or embed the value when the zero value should work. Code: Job in Go.
sync.Mutex embedding and copying locks Must-know
In plain words: embedding sync.Mutex makes Lock and Unlock methods of your type, which anyone importing the package can call. And any copy of the struct copies the lock.
Common misunderstanding: "Embedding the mutex is the idiom because it is shorter." It leaks synchronisation into the public API and invites callers to lock from outside. The idiom in the standard library is an unexported field (mu sync.Mutex) next to the data it protects.
Definition: the sync source: "A Mutex must not be copied after first use." The copylocks vet analyzer reports value receivers and assignments that copy a lock: Balance passes lock by value: ... contains sync.Mutex and assignment copies lock value to b: ... contains sync.Mutex. The fix is a pointer receiver for every method and never copying the struct after use.
1 type Account struct { mu sync.Mutex; bal int }
2 func (a Account) Balance() int vet: Balance passes lock by value
3 g1: a.mu.Lock() a.mu is locked
4 g2: b := a b.mu is a copy of a LOCKED mutex
5 g2: b.mu.Lock() blocks forever: nobody will unlock b.muReal scenario: a cache struct returned by value from a constructor; a struct with a mutex stored in a map[string]Account (each read copies); range over a slice of structs containing mutexes.
| Design | Public API includes Lock/Unlock | Copy-safe | vet catches copies |
|---|---|---|---|
type C struct { sync.Mutex; ... } | Yes | No | Yes |
type C struct { mu sync.Mutex; ... } with *C methods | No | No (still must not copy) | Yes |
type C struct { mu *sync.Mutex } | No | Copies share the lock | No (hides bugs) |
Fix / how to use it: unexported mu, pointer receivers, constructors returning *T, go vet in CI, go test -race. Code: mutexembed in Solutions.
Struct tags Must-know
In plain words: a tag is a raw string after a field. The compiler ignores it; libraries read it with reflect and decide what it means: json:"email" renames the JSON key, db:"email" names the column, validate:"required,email" adds rules.
Common misunderstanding: "A malformed tag is a compile error." It is a valid string; encoding/json just ignores the bad key. json:name (no quotes) silently does nothing; only the structtag vet check catches it: struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag value.
Definition: spec: "A field declaration may be followed by an optional string literal tag ... An empty tag string is equivalent to an absent tag." reflect.StructTag: "By convention, tag strings are a concatenation of optionally space-separated key:"value" pairs." Get(key) returns the value or ""; Lookup(key) also reports whether the key was present ("To determine whether a tag is explicitly set to the empty string, use [StructTag.Lookup]"). Tags are part of type identity: two struct types differing only in tags are different types but convertible. The structtag vet analyzer "check[s] that struct field tags conform to reflect.StructTag.Get" and also reports "certain struct tags (json, xml) used with unexported fields."
1 field: Email string `json:"email" db:"email" validate:"required,email"`
2 json.Marshal -> reflect: f.Tag.Get("json") = "email" -> key "email"
3 SQL mapper -> f.Tag.Lookup("db") = ("email", true) -> column email
4 validator -> f.Tag.Get("validate") = "required,email" -> rules
5 typo `json:email` -> Get returns "" -> key "Email"; only go vet reports itReal scenario: an API that returns "Email" instead of "email" because of a missing quote; a password hash marshalled into a response because json:"-" was forgotten; a column mismatch between a db tag and a migration; a validate tag silently ignored after a library upgrade changed the key name.
| Tag key | Read by | Common options |
|---|---|---|
json | encoding/json | name, omitempty, omitzero (Go 1.24), string, -, -, |
xml | encoding/xml | name, attr, chardata, innerxml, omitempty |
db | sqlx, scany and hand-written mappers (not database/sql) | Column name; library-specific options |
yaml | gopkg.in/yaml.v3 and similar | name, omitempty, inline |
validate | go-playground/validator and similar | Rule list, comma-separated |
protobuf | Generated code, protoreflect | Field number, wire type |
env, mapstructure, form | Config and form binders | Library-specific |
Fix / how to use it: run go vet; test the serialised output (a golden JSON test); keep one tag key per library; read tags with Lookup when empty is meaningful. Code: tags in Solutions. JSON details belong to JSON, XML, Struct Tags.
Unexported fields, JSON and encoding pointers Important
In plain words: lower-case fields are invisible to other packages, including encoding/json, reflect-based mappers and go-cmp. And decoders must receive a pointer, otherwise they have nothing to write into.
Common misunderstanding: "json:"age" on an unexported field exports it." The tag is ignored; vet reports struct field age has json tag but is not exported. And "json.Unmarshal(data, u) fills u": vet reports call of Unmarshal passes non-pointer as second argument; at run time it returns json: Unmarshal(non-pointer tags.User).
Definition: encoding/json: "Each exported struct field becomes a member of the object"; unexported non-embedded fields are skipped. Decoders, encoding.TextUnmarshaler and json.Unmarshaler methods use pointer receivers because they fill the receiver. MarshalJSON with a pointer receiver is not called for non-addressable values (a value stored in an interface or a map), the method-set rule again.
Real scenario: a domain type with unexported fields marshalled as {}; a MarshalJSON on *Money ignored when Money sits in a map[string]Money; a decoder writing into a copy.
Fix / how to use it: separate DTO structs with exported, tagged fields for the wire, mapped to domain types with unexported fields; value receivers on MarshalJSON/MarshalText, pointer receivers on UnmarshalJSON/UnmarshalText. Code: TestUnmarshalNeedsPointer in tags.
Field alignment and padding Good to know
In plain words: the CPU wants an int64 at an address divisible by 8. The compiler inserts unused bytes (padding) between fields to keep that rule, so field order changes the size of a struct.
Common misunderstanding: "Reordering fields always makes code faster." It reduces memory, which matters for millions of values in a slice or cache. For one struct it does nothing, and the most compact order can put two hot fields updated by different goroutines on the same cache line ("false sharing", as the fieldalignment doc warns).
Definition: each type has an alignment (unsafe.Alignof): 1 for bool/int8, 2 for int16, 4 for int32/float32, 8 for int64, pointers, strings, slices and interfaces on 64-bit platforms. A field's offset (unsafe.Offsetof) is rounded up to its alignment; the struct's alignment is its largest field alignment; the size (unsafe.Sizeof) is rounded up to that alignment. The fieldalignment analyzer in golang.org/x/tools finds "structs that would use less memory if their fields were sorted"; it "is not included in typical suites such as vet or gopls", but golangci-lint can enable it through its govet linter settings.
1 Loose { Active bool; ID int64; Ready bool; Count int32; Admin bool }
2 offsets 0, 8, 16, 20, 24 ; size 32 (17 bytes padding)
3 Tight { ID int64; Count int32; Active, Ready, Admin bool }
4 offsets 0, 8, 12, 13, 14 ; size 16 (1 byte padding)
5 4 194 304 values: 128 MiB vs 64 MiB; sum over ID measured 4.98 ms vs 3.87 ms (Apple M4 Pro)Real scenario: an in-memory cache of 50 million small records; a slice of events in a stream processor; a struct embedded in every row of an analytics job. Equally real: a pair of counters updated by different goroutines that should be padded apart, not packed together.
Fix / how to use it: order fields from largest to smallest alignment for types with many instances; keep logical order elsewhere; measure with unsafe.Sizeof in a test. Code: layout in Solutions. Memory layout of pointers themselves is in Pointers.
Copying structs and slices of structs Must-know
In plain words: for _, v := range items gives you a copy of each element; changing v changes nothing in the slice. items[i].Qty++ changes the element.
Common misunderstanding: "Go 1.22 fixed the range copy." Go 1.22 made each iteration's v a new variable (so &v or closures no longer share one variable); v is still a copy of the element. Another one: "p := &items[0] stays valid." It stays valid memory, but after an append that reallocates it points into the old array and stops tracking the slice.
Definition: assignment, passing as an argument, returning, ranging and storing in an interface all copy the struct value (shallowly). []T stores values contiguously (cache-friendly, fewer pointers for the GC, copies on range); []*T stores pointers (cheap to range and mutate, more allocations and pointer chasing).
1 items := []Item{{"A",1},{"B",1}}
2 for _, v := range items { v.Qty++ } items unchanged: v is a copy
3 for i := range items { items[i].Qty++ } items = [{A 2} {B 2}]
4 p := &items[0]; items = append(items, x) if cap was full: new array; p points at the old one
5 p.Qty = 99 items[0].Qty still 2Real scenario: a price update loop that "does nothing"; a cart that loses a quantity change after adding an item; a handler that stores &users[i] in a cache and later appends to users.
| Choice | Good for | Cost |
|---|---|---|
[]T | Small/medium structs, read-mostly, bulk processing | Range copies; pointers into it go stale on append |
[]*T | Large structs, shared identity, frequent in-place mutation | One allocation per element, GC scanning, nil checks |
map[K]T | Small values, replaced whole | Cannot mutate fields in place |
map[K]*T | Entities mutated in place | Same as []*T |
Fix / how to use it: mutate through the index; take pointers only after the slice stops growing; choose []*T for entities with identity. Code: equality in Solutions; slice growth in Arrays, Slices & Maps.
Getters, setters and Stringer Important
In plain words: Go getters are named after the field without Get: Owner(), not GetOwner(). Setters are SetOwner. A String() string method controls how fmt prints the value.
Common misunderstanding: "Every field needs a getter and setter." Plain data types use exported fields. Getters exist to protect invariants (unexported field, validated setter) or to satisfy an interface. And "String() hides secrets everywhere": %#v uses GoString, not String, and a pointer-receiver String is skipped for values.
Definition: Effective Go: "If you have a field called owner (lower case, unexported), the getter method should be called Owner (upper case, exported), not GetOwner." fmt.Stringer: "The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as [Print]." fmt.GoStringer handles %#v. Calling fmt.Sprint(x) inside x.String() recurses forever; convert to a different type first.
Real scenario: a Credentials struct logged in an error message; an enum Status printed as 1 in logs; a GetID() method inherited from protobuf style in hand-written code.
Fix / how to use it: value-receiver String and GoString for redaction; stringer (golang.org/x/tools/cmd/stringer) for enums with many values. Code: stringer in Solutions.
Comparing structs: ==, Equal, DeepEqual, go-cmp Important
In plain words: == compares fields exactly; an Equal method expresses domain equality; reflect.DeepEqual walks any value recursively; go-cmp's cmp.Equal and cmp.Diff are the test-time tool with readable diffs.
Common misunderstanding: "reflect.DeepEqual is the safe general ==." It compares unexported fields too (so two equal time.Time values with different monotonic readings differ), distinguishes nil from empty slices, and is slow. And "cmp.Equal is fine in production": its own documentation says its "propensity towards panicking means that its unsuitable for production environments where a spurious panic may be fatal."
Definition: reflect.DeepEqual: "Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal." cmp.Equal uses an Equal method when the type has one ("Types with an Equal method (e.g., [time.Time.Equal]) may use that method"), and "If a struct contains unexported fields, Equal panics unless an [Ignore] option ... ignores that field or the [Exporter] option explicitly permits comparing the unexported field."
| Tool | Unexported fields | Uses Equal method | nil vs empty slice | Where |
|---|---|---|---|---|
== | Yes (same package rules irrelevant) | No | Not comparable | Production; comparable types only |
Equal method | Your choice | It is the method | Your choice | Production; domain equality |
slices.Equal, maps.Equal | n/a | No (uses == on elements) | Equal | Production |
reflect.DeepEqual | Yes | No | Different | Tests, rarely production |
cmp.Equal / cmp.Diff | Panics unless options | Yes | Different by default (cmpopts.EquateEmpty) | Tests |
Fix / how to use it: Equal methods for value objects, cmp.Diff in tests (if d := cmp.Diff(want, got); d != "" { t.Errorf("mismatch (-want +got):\n%s", d) }), never == on time.Time fields. The module uses only the standard library; go-cmp is shown in prose. Code: equality in Solutions.
Immutability conventions Important
In plain words: Go has no readonly or final for fields. An immutable type is a convention: unexported fields, a validating constructor, value receivers, and methods that return a modified copy (WithStatus), with slices and maps copied in and out.
Common misunderstanding: "Value receivers make a type immutable." A value receiver copies the struct, but a slice or map field in the copy shares the same backing storage, so o.lines[0] = "x" or an append within capacity changes what the original sees.
Definition: convention-level immutability: no exported fields, no pointer-receiver mutators, defensive copies (slices.Clone) at every boundary, and slices.Clip before append in With methods so a new array is allocated.
1 o1 := NewOrder("o-1", in) lines cloned from caller's slice
2 in[0] = "changed" o1 unaffected
3 o2 := o1.WithLine("pen") Clip forces a new array
4 o3 := o1.WithLine("mug") o2 still "book,pen" (no shared array)
5 o2.Lines()[0] = "tampered" Lines returns a clone; o2 unaffectedReal scenario: a Money or Address value object passed between goroutines without locks; an order snapshot published as an event; configuration shared read-only across request handlers.
Fix / how to use it: value objects as described; for read-mostly shared state, build a new value and swap an atomic.Pointer[T]. Code: Order in stringer, Solutions; design rules in Entities & Value Objects.
Generics with structs Good to know
In plain words: a struct type can have type parameters (Page[T]). Generic code that needs to call a pointer-receiver method on T uses a second type parameter constrained to "pointer to T with this method".
Common misunderstanding: "func DecodeAll[T Decoder]() lets me call Decode on a new T." If Decode has a pointer receiver, T (say SKU) does not satisfy Decoder; *SKU does, but then a zero T is a nil pointer. The PT interface{ *T; Decoder } constraint solves it. And "methods can have their own type parameters": only from Go 1.27.
Definition: a generic type type Page[T any] struct{ Items []T } is instantiated as Page[SKU]. A constraint with a type element *T plus methods lets PT(&out[i]).Decode(s) compile; callers write DecodeAll[SKU](in) and PT is inferred. Go 1.27 adds generic methods ("a method declaration may declare its own type parameters"), which cannot implement interface methods.
1 type PtrDecoder[T any] interface { *T; Decoder }
2 DecodeAll[SKU](in) T = SKU, PT inferred = *SKU
3 out := make([]SKU, n) zero values, addressable
4 PT(&out[i]).Decode(s) calls (*SKU).Decode on the element
5 go1.27: func (b *Bag) Filter[T any]() []T generic method; not in go1.24 modulesReal scenario: a paginated API response type reused for every resource; a repository helper that scans rows into any struct with a Scan pointer method; a generic Set[T comparable] struct{ m map[T]struct{} }.
Fix / how to use it: generic structs for containers and envelopes; pointer-method constraints for decode/scan helpers. Code: generic in Solutions; the full story is in Generics.
Go
Before
A PHP-shaped design ported literally: a base type with a "hook", an embedding type that "overrides" it, and a decorator that would need a subclass per method. In Go the override silently does not take part in the base method:
type Animal struct{ Name string }
func (a Animal) Sound() string { return "..." }
func (a Animal) Describe() string { return a.Name + " says " + a.Sound() } // always Animal.Sound
type Dog struct{ Animal }
func (d Dog) Sound() string { return "woof" }
// Dog{Animal{"Rex"}}.Describe() == "Rex says ..." (expected "Rex says woof")After
The same package rewritten with Go's tools: promotion for shared fields (Timestamps), an interface for the varying behaviour (Speaker, DescribeAny), an embedded interface for a decorator that overrides one method (CountingStore), and an embedded pointer with a constructor that makes it non-nil (NewJob).
// Package embedding shows promotion, shadowing, the absence of virtual
// dispatch, embedded pointers and interface embedding for decoration.
package embedding
import (
"context"
"errors"
"fmt"
"sync/atomic"
"time"
)
// Timestamps is reused by several entities.
type Timestamps struct {
CreatedAt time.Time
UpdatedAt time.Time
}
// Touch updates UpdatedAt; promoted to every struct that embeds Timestamps.
func (t *Timestamps) Touch(now time.Time) { t.UpdatedAt = now }
// Animal is the "base" a Java or PHP developer would write.
type Animal struct{ Name string }
// Sound is meant to be "overridden".
func (a Animal) Sound() string { return "..." }
// Describe calls a.Sound(). In Go this is ALWAYS Animal.Sound:
// there is no virtual dispatch on concrete types.
func (a Animal) Describe() string { return a.Name + " says " + a.Sound() }
// Dog embeds Animal and shadows Sound.
type Dog struct {
Animal
Timestamps
}
// Sound shadows Animal.Sound for calls made on a Dog.
func (d Dog) Sound() string { return "woof" }
// Speaker is how Go gets dynamic dispatch: through an interface.
type Speaker interface{ Sound() string }
// DescribeAny is the Go answer to the template-method pattern: pass
// the behaviour in as an interface instead of relying on overriding.
func DescribeAny(name string, s Speaker) string { return name + " says " + s.Sound() }
// Store is a dependency with several methods.
type Store interface {
Get(ctx context.Context, key string) (string, error)
Put(ctx context.Context, key, val string) error
Delete(ctx context.Context, key string) error
}
// ErrNotFound is returned by MapStore.Get for a missing key.
var ErrNotFound = errors.New("not found")
// MapStore is an in-memory Store (not safe for concurrent use).
type MapStore map[string]string
func (m MapStore) Get(_ context.Context, k string) (string, error) {
v, ok := m[k]
if !ok {
return "", fmt.Errorf("get %q: %w", k, ErrNotFound)
}
return v, nil
}
func (m MapStore) Put(_ context.Context, k, v string) error { m[k] = v; return nil }
func (m MapStore) Delete(_ context.Context, k string) error { delete(m, k); return nil }
// CountingStore decorates any Store: it embeds the interface, so Put and
// Delete are promoted unchanged, and it overrides only Get.
type CountingStore struct {
Store
gets atomic.Int64
}
// Get counts, then forwards explicitly to the embedded Store.
func (c *CountingStore) Get(ctx context.Context, k string) (string, error) {
c.gets.Add(1)
return c.Store.Get(ctx, k)
}
// Gets reports how many Get calls went through the decorator.
func (c *CountingStore) Gets() int64 { return c.gets.Load() }
// Logger is embedded by pointer in Job, as in Effective Go.
type Logger struct{ lines []string }
func (l *Logger) Printf(format string, args ...any) {
l.lines = append(l.lines, fmt.Sprintf(format, args...))
}
// Job embeds *Logger: the zero Job has a nil Logger, and job.Printf panics.
type Job struct {
Command string
*Logger
}
// NewJob makes the embedded pointer non-nil, which is why it exists.
func NewJob(cmd string) *Job { return &Job{Command: cmd, Logger: &Logger{}} }
// Printf refines the promoted method and calls the embedded one by its field name.
func (j *Job) Printf(format string, args ...any) {
j.Logger.Printf("%q: "+format, append([]any{j.Command}, args...)...)
}package embedding
import (
"context"
"errors"
"strings"
"testing"
"time"
)
func TestPromotionAndShadowing(t *testing.T) {
d := Dog{Animal: Animal{Name: "Rex"}}
d.Touch(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)) // promoted from *Timestamps; d is addressable
if d.UpdatedAt.Year() != 2026 || d.Timestamps.UpdatedAt != d.UpdatedAt {
t.Fatal("promoted field and full path must be the same field")
}
if d.Name != "Rex" || d.Sound() != "woof" || d.Animal.Sound() != "..." {
t.Fatalf("shadowing broken: %q %q", d.Sound(), d.Animal.Sound())
}
}
func TestNoVirtualDispatch(t *testing.T) {
d := Dog{Animal: Animal{Name: "Rex"}}
// Describe is promoted from Animal; inside it the receiver is the Animal, not the Dog.
if got := d.Describe(); got != "Rex says ..." {
t.Fatalf("Describe = %q", got)
}
// Dynamic dispatch happens through an interface.
if got := DescribeAny(d.Name, d); got != "Rex says woof" {
t.Fatalf("DescribeAny = %q", got)
}
}
func TestDecoratorViaEmbeddedInterface(t *testing.T) {
ctx := context.Background()
cs := &CountingStore{Store: MapStore{}}
var s Store = cs // *CountingStore satisfies Store: Put/Delete promoted, Get overridden
_ = s.Put(ctx, "k", "v")
if v, err := s.Get(ctx, "k"); err != nil || v != "v" {
t.Fatalf("Get = %q, %v", v, err)
}
if _, err := s.Get(ctx, "missing"); !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v", err)
}
if cs.Gets() != 2 {
t.Fatalf("Gets = %d, want 2", cs.Gets())
}
}
func TestNilEmbeddedInterfacePanics(t *testing.T) {
defer func() {
r := recover()
if r == nil || !strings.Contains(r.(error).Error(), "nil pointer dereference") {
t.Fatalf("recover() = %v", r)
}
}()
var cs CountingStore // Store is nil
_ = cs.Put(context.Background(), "k", "v")
}
func TestEmbeddedPointer(t *testing.T) {
j := NewJob("backup")
j.Printf("started %d", 1)
if got := j.lines[0]; got != `"backup": started 1` {
t.Fatalf("line = %q", got)
}
defer func() {
if recover() == nil {
t.Fatal("zero Job with nil *Logger must panic on Printf")
}
}()
var zero Job
zero.Logger.Printf("boom") // nil *Logger: append through l.lines dereferences nil
}The Go angle
| Package or tool | What it does with structs |
|---|---|
reflect | Type.Field(i), StructField.Tag, StructTag.Get/Lookup, IsExported, Anonymous (embedded); Go 1.26 adds Type.Fields() iterators |
encoding/json, encoding/xml | Exported fields only, tags, embedded struct flattening, omitempty, omitzero |
encoding | TextMarshaler/TextUnmarshaler, BinaryMarshaler; Go 1.24 adds TextAppender/BinaryAppender |
fmt | %v prints {a b}, %+v prints {Name:a Age:b}, %#v prints Go syntax; Stringer, GoStringer, Formatter |
unsafe | Sizeof, Alignof, Offsetof for layout tests |
go vet | composites, copylocks, structtag, unmarshal, printf (wrong verb for a struct field) |
golang.org/x/tools analyzers | fieldalignment (standalone or via golangci-lint govet) |
go/types | The type checker; compileerrs uses it to pin compiler messages in tests |
Mechanics
Selector resolution, step by step Must-know
For x.f the compiler walks the embedding tree breadth-first by depth:
1 depth 0: fields and methods declared on x's type (or *x's base type)
2 depth 1: fields and methods of each embedded field
3 depth 2: of their embedded fields, and so on
4 stop at the first depth where f exists
5 exactly one f at that depth -> x.f is legal ; more than one -> ambiguous selector x.f
6 x is a pointer to a struct: x.f means (*x).f ; through embedded *T: implicit dereference at each step| Case | Result |
|---|---|
f at depth 0 and depth 1 | Depth 0 wins (shadowing) |
f twice at depth 1, never used | Compiles |
f twice at depth 1, used | ambiguous selector x.f |
f at depth 1 via an embedded nil *T, then read | Runtime nil pointer dereference |
encoding/json, two same-depth fields, same JSON name, neither tagged | Both silently dropped |
Method set rules Must-know
| Type | Contains methods with receiver |
|---|---|
T | T |
*T | T and *T |
S embedding T | S, plus promoted T |
*S embedding T | S, *S, promoted T and *T |
S or *S embedding *T | Their own, plus promoted T and *T |
S embedding interface I | S (and *S for *S), plus all of I |
Layout rules on amd64 and arm64 Good to know
| Field type | Size | Alignment |
|---|---|---|
bool, int8, uint8 | 1 | 1 |
int16 | 2 | 2 |
int32, float32, rune | 4 | 4 |
int64, float64, int, uintptr, pointer, map, chan, func | 8 | 8 |
string | 16 | 8 |
[]T | 24 | 8 |
any / interface | 16 | 8 |
struct{} | 0 | 1 |
On 32-bit platforms int64 has 4-byte alignment, which is why 64-bit atomics on struct fields needed care before atomic.Int64 (which is always 8-byte aligned).
Exact error texts Must-know
Captured with Go 1.27.4 (go build, go vet, go run) on the programs in the Lab; the type-checker ones are pinned by compileerrs.
| Source | Text |
|---|---|
| compiler | ambiguous selector c.Close |
| compiler | cannot use Counter{} (value of struct type Counter) as fmt.Stringer value in variable declaration: Counter does not implement fmt.Stringer (method String has pointer receiver) |
| compiler | cannot call pointer method Inc on Counter |
| compiler | cannot assign to struct field m["a"].n in map |
| compiler | too few values in struct literal of type P |
| compiler | mixture of field:value and value elements in struct literal |
| compiler | invalid operation: a == b (struct containing []string cannot be compared) |
| compiler | invalid map key type Order |
| compiler | invalid recursive type: Node refers to itself |
| compiler | use of promoted field Base.ID in struct literal of type User requires go1.27 or later (-lang was set to go1.24; check go.mod) |
| vet composites | net.DNSConfigError struct literal uses unkeyed fields |
| vet copylocks | Balance passes lock by value: errs/unkeyedvet.Account contains sync.Mutex |
| vet copylocks | assignment copies lock value to b: errs/unkeyedvet.Account contains sync.Mutex |
| vet structtag | struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag value |
| vet structtag | struct field age has json tag but is not exported |
| vet unmarshal | call of Unmarshal passes non-pointer as second argument |
| runtime | panic: runtime error: invalid memory address or nil pointer dereference |
| runtime | json: Unmarshal(non-pointer tags.User) (an error value, not a panic) |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Literals break on upgrades | Keyed literals | T{Field: v}; vet composites | Survives new fields | Slightly longer |
| Invalid values in the system | Validating constructor | Unexported fields + NewX returning error | Invariant holds everywhere | Zero value still exists |
| Constructor with ten parameters | Options or config struct | WithX funcs, or Config with zero defaults | Grows without breaking callers | More code |
| Mutation lost | Pointer receivers | func (c *T) for all methods | Visible updates | T loses interface methods |
| Interface not satisfied | Assign &v; compile-time assertion | var _ I = (*T)(nil) | Fails at build time | None |
| Override not called | Interface for the varying step | DescribeAny(name, Speaker) | Real dynamic dispatch | Explicit wiring |
| Decorate one method | Embedded interface | type C struct{ Store } + one method | Minimal forwarding | Nil inner value panics |
| Lock leaks into API, lock copied | Unexported mu, pointer receivers | mu sync.Mutex | Encapsulated | Must never copy |
| Silent tag typos | go vet, golden tests | structtag analyzer | Caught in CI | Libraries' custom keys unchecked |
| Wasted memory at scale | Reorder fields | Largest alignment first; fieldalignment | Up to 2× less memory | Readability; false sharing |
| Range loop does nothing | Index form | for i := range s { s[i].X++ } | Mutates in place | None |
| Flaky struct equality in tests | Equal methods, cmp.Diff | time.Time.Equal, options | Readable diffs | Test dependency |
| Value object mutated through slice | Defensive copies | slices.Clone, slices.Clip | Real immutability | Allocations |
Literals, zero values and anonymous structs
// Package literals shows struct declaration, keyed and positional
// literals, anonymous structs, comparability and useful zero values.
package literals
import (
"bytes"
"sync"
"time"
)
// Address is comparable: every field type is comparable.
type Address struct {
Street string
City string
Country string // ISO 3166-1 alpha-2
}
// Customer embeds nothing yet; it mixes comparable and non-comparable fields.
type Customer struct {
ID int64
Name string
Address Address
Tags []string // a slice makes Customer NOT comparable with ==
}
// Keyed is the form to use for types you do not own: adding a field
// to Address later does not break this line.
func Keyed() Address {
return Address{City: "Berlin", Country: "DE"} // Street gets its zero value ""
}
// Positional must list every field in declaration order. It is fine for
// small local types (points, pairs) and fragile everywhere else.
func Positional() Address {
return Address{"Unter den Linden 1", "Berlin", "DE"}
}
// DedupAddresses uses Address as a map key, which works only because
// Address is comparable.
func DedupAddresses(in []Address) []Address {
seen := make(map[Address]struct{}, len(in))
out := in[:0:0]
for _, a := range in {
if _, ok := seen[a]; ok {
continue
}
seen[a] = struct{}{} // struct{} is the zero-size set value
out = append(out, a)
}
return out
}
// TestCase shows the most common anonymous struct: a table of test inputs.
var TestCase = []struct {
Name string
In Address
Want bool
}{
{Name: "full", In: Address{"a", "b", "DE"}, Want: true},
{Name: "no country", In: Address{Street: "a"}, Want: false},
}
// Valid is the function the table above describes.
func Valid(a Address) bool { return a.Country != "" }
// AuditLog has a useful zero value: var l AuditLog is ready to use,
// because sync.Mutex and bytes.Buffer are both ready at their zero value.
type AuditLog struct {
mu sync.Mutex
buf bytes.Buffer
now func() time.Time // nil means time.Now; zero value still works
}
// Record appends one line; it needs a pointer receiver because it mutates.
func (l *AuditLog) Record(event string) {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now
if l.now != nil {
now = l.now
}
l.buf.WriteString(now().UTC().Format(time.RFC3339) + " " + event + "\n")
}
// String returns everything recorded so far.
func (l *AuditLog) String() string {
l.mu.Lock()
defer l.mu.Unlock()
return l.buf.String()
}package literals
import (
"strings"
"testing"
"time"
)
func TestKeyedAndPositionalAreEqual(t *testing.T) {
k := Keyed()
k.Street = "Unter den Linden 1"
if k != Positional() { // == compares field by field, in declaration order
t.Fatalf("got %+v, want %+v", k, Positional())
}
}
func TestDedup(t *testing.T) {
a := Address{"s", "c", "DE"}
got := DedupAddresses([]Address{a, a, {City: "x"}})
if len(got) != 2 {
t.Fatalf("len = %d, want 2", len(got))
}
}
func TestTable(t *testing.T) {
for _, tc := range TestCase {
t.Run(tc.Name, func(t *testing.T) {
if got := Valid(tc.In); got != tc.Want {
t.Fatalf("Valid(%+v) = %v, want %v", tc.In, got, tc.Want)
}
})
}
}
func TestAnonymousStructsAssignable(t *testing.T) {
// Two anonymous struct types with identical fields (and tags) are identical types.
p := struct{ X, Y int }{1, 2}
var q struct{ X, Y int } = p
if p != q {
t.Fatal("identical anonymous structs must compare equal")
}
}
func TestZeroValueAuditLog(t *testing.T) {
var l AuditLog // no constructor
l.now = func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }
l.Record("login")
if got := l.String(); !strings.HasPrefix(got, "2026-01-02T03:04:05Z login") {
t.Fatalf("got %q", got)
}
}Constructors and functional options
// Package constructors shows NewX functions: validation, returning a
// pointer or a value, a Config struct, and functional options.
package constructors
import (
"errors"
"fmt"
"log/slog"
"time"
)
// Money is a small value type: NewMoney returns a value, not a pointer.
type Money struct {
cents int64
currency string
}
// ErrCurrency is returned for anything that is not a three-letter code.
var ErrCurrency = errors.New("currency must be a 3-letter ISO 4217 code")
// NewMoney validates once, so every Money in the program is valid.
func NewMoney(cents int64, currency string) (Money, error) {
if len(currency) != 3 {
return Money{}, fmt.Errorf("NewMoney(%d, %q): %w", cents, currency, ErrCurrency)
}
return Money{cents: cents, currency: currency}, nil
}
// Cents and Currency are getters: no Get prefix.
func (m Money) Cents() int64 { return m.cents }
func (m Money) Currency() string { return m.currency }
func (m Money) String() string {
return fmt.Sprintf("%d.%02d %s", m.cents/100, m.cents%100, m.currency)
}
func (m Money) IsZero() bool { return m == Money{} }
func (m Money) Add(o Money) Money { return Money{cents: m.cents + o.cents, currency: m.currency} }
// Client is a large, stateful type: NewClient returns a pointer.
type Client struct {
baseURL string
timeout time.Duration
retries int
logger *slog.Logger
}
// Option is a functional option (Rob Pike 2014, Dave Cheney 2014).
type Option func(*Client) error
// WithTimeout overrides the default timeout.
func WithTimeout(d time.Duration) Option {
return func(c *Client) error {
if d <= 0 {
return fmt.Errorf("timeout must be positive, got %s", d)
}
c.timeout = d
return nil
}
}
// WithRetries overrides the default retry count.
func WithRetries(n int) Option {
return func(c *Client) error {
if n < 0 || n > 10 {
return fmt.Errorf("retries must be in [0,10], got %d", n)
}
c.retries = n
return nil
}
}
// WithLogger sets a logger; nil keeps the default.
func WithLogger(l *slog.Logger) Option {
return func(c *Client) error {
if l != nil {
c.logger = l
}
return nil
}
}
// NewClient sets defaults first, then applies options in order, then
// validates the required argument. Callers cannot get a half-built Client.
func NewClient(baseURL string, opts ...Option) (*Client, error) {
if baseURL == "" {
return nil, errors.New("NewClient: baseURL is required")
}
c := &Client{
baseURL: baseURL,
timeout: 5 * time.Second,
retries: 2,
logger: slog.Default(),
}
for _, opt := range opts {
if err := opt(c); err != nil {
return nil, fmt.Errorf("NewClient: %w", err)
}
}
return c, nil
}
// Timeout and Retries expose the effective settings for tests and logs.
func (c *Client) Timeout() time.Duration { return c.timeout }
func (c *Client) Retries() int { return c.retries }
// Config is the other common style: one exported struct whose zero
// value means "defaults". It is easier to load from a file or env.
type Config struct {
BaseURL string
Timeout time.Duration // 0 means 5s
Retries *int // nil means 2; a pointer distinguishes "unset" from 0
}
// NewClientFromConfig maps a Config onto the same options.
func NewClientFromConfig(cfg Config) (*Client, error) {
var opts []Option
if cfg.Timeout != 0 {
opts = append(opts, WithTimeout(cfg.Timeout))
}
if cfg.Retries != nil {
opts = append(opts, WithRetries(*cfg.Retries))
}
return NewClient(cfg.BaseURL, opts...)
}package constructors
import (
"errors"
"testing"
"time"
)
func TestNewMoney(t *testing.T) {
m, err := NewMoney(1999, "EUR")
if err != nil {
t.Fatal(err)
}
if got := m.String(); got != "19.99 EUR" {
t.Fatalf("String() = %q", got)
}
if _, err := NewMoney(1, "euro"); !errors.Is(err, ErrCurrency) {
t.Fatalf("err = %v, want ErrCurrency", err)
}
if !(Money{}).IsZero() {
t.Fatal("zero Money must report IsZero")
}
}
func TestNewClientDefaultsAndOptions(t *testing.T) {
c, err := NewClient("https://api.example.com")
if err != nil {
t.Fatal(err)
}
if c.Timeout() != 5*time.Second || c.Retries() != 2 {
t.Fatalf("defaults = %s/%d", c.Timeout(), c.Retries())
}
c, err = NewClient("https://api.example.com", WithTimeout(time.Second), WithRetries(0))
if err != nil {
t.Fatal(err)
}
if c.Timeout() != time.Second || c.Retries() != 0 {
t.Fatalf("options not applied: %s/%d", c.Timeout(), c.Retries())
}
}
func TestNewClientRejectsBadInput(t *testing.T) {
cases := []struct {
name string
url string
opts []Option
want string
}{
{"no url", "", nil, "NewClient: baseURL is required"},
{"bad timeout", "u", []Option{WithTimeout(-1)}, "NewClient: timeout must be positive, got -1ns"},
{"bad retries", "u", []Option{WithRetries(99)}, "NewClient: retries must be in [0,10], got 99"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, err := NewClient(tc.url, tc.opts...)
if c != nil || err == nil || err.Error() != tc.want {
t.Fatalf("got (%v, %v), want (nil, %q)", c, err, tc.want)
}
})
}
}
func TestConfigZeroMeansDefault(t *testing.T) {
zero := 0
c, err := NewClientFromConfig(Config{BaseURL: "u", Retries: &zero})
if err != nil {
t.Fatal(err)
}
if c.Timeout() != 5*time.Second || c.Retries() != 0 {
t.Fatalf("got %s/%d", c.Timeout(), c.Retries())
}
}Receivers, nil receivers, method sets and addressability
// Package receivers shows value vs pointer receivers, nil receivers,
// method sets, addressability and method values.
package receivers
import (
"fmt"
"strings"
)
// Counter mutates, so every method uses a pointer receiver (do not mix).
type Counter struct {
name string
n int
}
// IncValue is the classic bug: it increments a copy.
func (c Counter) IncValue() { c.n++ } //nolint:staticcheck // deliberate: shows the lost update
// Inc mutates the caller's Counter.
func (c *Counter) Inc() { c.n++ }
// N reads the value. A pointer receiver here keeps the method set uniform.
func (c *Counter) N() int { return c.n }
// String has a pointer receiver, so only *Counter is a fmt.Stringer.
func (c *Counter) String() string { return fmt.Sprintf("%s=%d", c.name, c.n) }
// Point is small and immutable: value receivers everywhere.
type Point struct{ X, Y float64 }
// Add returns a new Point and never changes p.
func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} }
// Tree shows a nil receiver that is a valid, meaningful value.
type Tree struct {
Val int
Left, Right *Tree
}
// Sum works on a nil *Tree: the empty tree sums to 0.
func (t *Tree) Sum() int {
if t == nil {
return 0
}
return t.Val + t.Left.Sum() + t.Right.Sum()
}
// Insert returns the (possibly new) root, so it also works on nil.
func (t *Tree) Insert(v int) *Tree {
if t == nil {
return &Tree{Val: v}
}
if v < t.Val {
t.Left = t.Left.Insert(v)
} else {
t.Right = t.Right.Insert(v)
}
return t
}
// Compile-time interface checks: the build fails if a method set changes.
var (
_ fmt.Stringer = (*Counter)(nil) // *Counter has String
_ fmt.Stringer = Point{} // Point has String (value receiver)
)
// String on a value receiver: both Point and *Point satisfy fmt.Stringer.
func (p Point) String() string { return fmt.Sprintf("(%g,%g)", p.X, p.Y) }
// IncAll shows addressability: a slice element is addressable, a map
// element is not (m[k].Inc() does not compile for map[string]Counter).
func IncAll(cs []Counter, m map[string]*Counter) {
for i := range cs {
cs[i].Inc() // the compiler rewrites this to (&cs[i]).Inc()
}
for _, c := range m {
c.Inc() // a map of pointers sidesteps the map-element rule
}
}
// Joined uses a method value (bound receiver) and a method expression
// (receiver becomes the first parameter).
func Joined(ps []Point, offset Point) string {
shift := offset.Add // method value: func(Point) Point, receiver copied now
toString := Point.String // method expression: func(Point) string
parts := make([]string, 0, len(ps))
for _, p := range ps {
parts = append(parts, toString(shift(p)))
}
return strings.Join(parts, " ")
}package receivers
import (
"fmt"
"testing"
)
func TestValueReceiverLosesUpdate(t *testing.T) {
c := Counter{name: "hits"}
c.IncValue()
if c.N() != 0 {
t.Fatalf("value receiver changed the caller: n=%d", c.N())
}
c.Inc() // c is addressable, so (&c).Inc()
if c.N() != 1 {
t.Fatalf("pointer receiver did not change the caller: n=%d", c.N())
}
}
func TestStringerAndMethodSets(t *testing.T) {
c := Counter{name: "hits", n: 3}
// The value does not have String in its method set, so fmt prints the fields.
if got := fmt.Sprint(c); got != "{hits 3}" {
t.Fatalf("Sprint(value) = %q", got)
}
if got := fmt.Sprint(&c); got != "hits=3" {
t.Fatalf("Sprint(pointer) = %q", got)
}
var s fmt.Stringer = &c // Counter{} here would not compile
_ = s
}
func TestNilReceiver(t *testing.T) {
var root *Tree
if root.Sum() != 0 {
t.Fatal("nil tree must sum to 0")
}
for _, v := range []int{5, 3, 8, 1} {
root = root.Insert(v)
}
if root.Sum() != 17 {
t.Fatalf("Sum = %d, want 17", root.Sum())
}
}
func TestAddressability(t *testing.T) {
cs := []Counter{{name: "a"}, {name: "b"}}
m := map[string]*Counter{"x": {name: "x"}}
IncAll(cs, m)
if cs[0].N() != 1 || cs[1].N() != 1 || m["x"].N() != 1 {
t.Fatalf("got %v %v %v", cs[0].N(), cs[1].N(), m["x"].N())
}
}
func TestMethodValueCopiesReceiver(t *testing.T) {
off := Point{1, 1}
got := Joined([]Point{{0, 0}, {2, 3}}, off)
if got != "(1,1) (3,4)" {
t.Fatalf("Joined = %q", got)
}
c := &Counter{name: "c"}
inc := c.Inc // method value with a pointer receiver binds the pointer
inc()
inc()
if c.N() != 2 {
t.Fatalf("n = %d, want 2", c.N())
}
}Mutex embedding vs a private lock
// Package mutexembed contrasts embedding sync.Mutex with a private mu field.
package mutexembed
import "sync"
// LeakyCache embeds sync.Mutex: Lock and Unlock are promoted and become part
// of LeakyCache's public API, so any caller can lock it (or forget to unlock).
type LeakyCache struct {
sync.Mutex
items map[string]string
}
// Set locks through the promoted method.
func (c *LeakyCache) Set(k, v string) {
c.Lock()
defer c.Unlock()
if c.items == nil {
c.items = make(map[string]string)
}
c.items[k] = v
}
// Cache keeps the lock private: the method set is only Get and Set.
type Cache struct {
mu sync.RWMutex
items map[string]string
}
// Set stores a value.
func (c *Cache) Set(k, v string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.items == nil {
c.items = make(map[string]string)
}
c.items[k] = v
}
// Get reads under a read lock.
func (c *Cache) Get(k string) (string, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
v, ok := c.items[k]
return v, ok
}
// Len must use a pointer receiver: a value receiver would copy the mutex
// (go vet: "Len passes lock by value").
func (c *Cache) Len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return len(c.items)
}package mutexembed
import (
"strconv"
"sync"
"testing"
)
func TestCacheConcurrent(t *testing.T) {
var c Cache // zero value is ready
var wg sync.WaitGroup
for i := range 50 {
wg.Add(1)
go func() {
defer wg.Done()
c.Set(strconv.Itoa(i), "v")
_, _ = c.Get("0")
}()
}
wg.Wait()
if c.Len() != 50 {
t.Fatalf("Len = %d", c.Len())
}
}
func TestLeakyCacheExposesLock(t *testing.T) {
var c LeakyCache
c.Lock() // compiles: the lock is part of the public API
c.items = map[string]string{"outside": "locked by a caller"}
c.Unlock()
c.Set("k", "v")
if len(c.items) != 2 {
t.Fatalf("len = %d", len(c.items))
}
}Struct tags, a db-tag mapper and JSON
The mapper builds the statement the architecture section's table expects. database/sql itself does not read tags; sqlx, scany and ORMs do, with their own option syntax.
// Package tags reads struct tags with reflect.StructTag and builds an
// INSERT statement from `db` tags, the way sqlx-style mappers do.
package tags
import (
"fmt"
"reflect"
"strings"
"time"
)
// User carries tags for three consumers: encoding/json, a SQL mapper
// and a validator. Each library reads only its own key.
type User struct {
ID int64 `json:"id" db:"id,pk"`
Email string `json:"email" db:"email" validate:"required,email"`
Name string `json:"name,omitempty" db:"name"`
Password string `json:"-" db:"password_hash"`
CreatedAt time.Time `json:"created_at,omitzero" db:"created_at"`
internal string // unexported: invisible to json, reflect-based mappers skip it
}
// Column describes one mapped field.
type Column struct {
Field string
Name string
PK bool
}
// Columns walks the exported fields of a struct type and parses the `db` key.
// A missing key falls back to the lower-cased field name; "-" skips the field.
func Columns(v any) ([]Column, error) {
t := reflect.TypeOf(v)
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("Columns: want struct, got %s", t.Kind())
}
var cols []Column
for i := range t.NumField() {
f := t.Field(i)
if !f.IsExported() {
continue
}
tag, ok := f.Tag.Lookup("db")
if tag == "-" {
continue
}
name, opts, _ := strings.Cut(tag, ",")
if !ok || name == "" {
name = strings.ToLower(f.Name)
}
cols = append(cols, Column{Field: f.Name, Name: name, PK: opts == "pk"})
}
return cols, nil
}
// InsertSQL builds a PostgreSQL INSERT with numbered placeholders, skipping
// the primary key (the database generates it) and returning it instead.
func InsertSQL(table string, v any) (string, []any, error) {
cols, err := Columns(v)
if err != nil {
return "", nil, err
}
rv := reflect.Indirect(reflect.ValueOf(v))
var names, marks []string
var args []any
pk := ""
for _, c := range cols {
if c.PK {
pk = c.Name
continue
}
names = append(names, c.Name)
args = append(args, rv.FieldByName(c.Field).Interface())
marks = append(marks, fmt.Sprintf("$%d", len(args)))
}
q := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", table, strings.Join(names, ", "), strings.Join(marks, ", "))
if pk != "" {
q += " RETURNING " + pk
}
return q, args, nil
}
// Rules returns the validate tag of every field that has one.
func Rules(v any) map[string]string {
out := map[string]string{}
t := reflect.TypeOf(v)
for i := range t.NumField() {
if r := t.Field(i).Tag.Get("validate"); r != "" {
out[t.Field(i).Name] = r
}
}
return out
}package tags
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func TestStructTagGetAndLookup(t *testing.T) {
f, _ := reflect.TypeOf(User{}).FieldByName("Name")
if got := f.Tag.Get("json"); got != "name,omitempty" {
t.Fatalf("Get(json) = %q", got)
}
if v, ok := f.Tag.Lookup("validate"); ok || v != "" {
t.Fatalf("Lookup(validate) = %q, %v; want absent", v, ok)
}
// Get cannot tell "absent" from "present but empty"; Lookup can.
tag := reflect.StructTag(`db:""`)
if v, ok := tag.Lookup("db"); !ok || v != "" {
t.Fatalf("Lookup on empty value = %q, %v", v, ok)
}
}
func TestInsertSQL(t *testing.T) {
u := User{Email: "dev@example.com", Name: "Dev", Password: "x", internal: "skip"}
q, args, err := InsertSQL("users", &u)
if err != nil {
t.Fatal(err)
}
want := "INSERT INTO users (email, name, password_hash, created_at) VALUES ($1, $2, $3, $4) RETURNING id"
if q != want {
t.Fatalf("q = %q\nwant %q", q, want)
}
if len(args) != 4 || args[0] != "dev@example.com" {
t.Fatalf("args = %v", args)
}
}
func TestJSONTags(t *testing.T) {
b, err := json.Marshal(User{ID: 7, Email: "dev@example.com", Password: "secret", internal: "x"})
if err != nil {
t.Fatal(err)
}
// Name omitted (omitempty, ""), CreatedAt omitted (omitzero, Go 1.24),
// Password omitted ("-"), internal omitted (unexported).
if got := string(b); got != `{"id":7,"email":"dev@example.com"}` {
t.Fatalf("json = %s", got)
}
var back User
if err := json.Unmarshal([]byte(`{"id":9,"name":"N","created_at":"2026-01-02T00:00:00Z"}`), &back); err != nil {
t.Fatal(err)
}
if back.ID != 9 || back.Name != "N" || !back.CreatedAt.Equal(time.Date(2026, 1, 2, 0, 0, 0, 0, time.UTC)) {
t.Fatalf("back = %+v", back)
}
}
func TestUnmarshalNeedsPointer(t *testing.T) {
var u User
// json.Unmarshal(data, u) is caught by go vet ("call of Unmarshal passes
// non-pointer as second argument"); through an any it reaches run time.
var target any = u
err := json.Unmarshal([]byte(`{"id":1}`), target)
if err == nil || err.Error() != "json: Unmarshal(non-pointer tags.User)" {
t.Fatalf("err = %v", err)
}
}
func TestRules(t *testing.T) {
if r := Rules(User{}); len(r) != 1 || r["Email"] != "required,email" {
t.Fatalf("Rules = %v", r)
}
}Measuring padding
// Package layout measures field alignment and padding with unsafe.Sizeof,
// Alignof and Offsetof (64-bit platforms: amd64, arm64).
package layout
// Loose orders fields as they came to mind: 7+4+7 bytes of padding.
type Loose struct {
Active bool // offset 0, then 7 bytes padding
ID int64 // offset 8
Ready bool // offset 16, then 3 bytes padding
Count int32 // offset 20
Admin bool // offset 24, then 7 bytes tail padding
}
// Tight has the same fields ordered from largest to smallest alignment.
type Tight struct {
ID int64 // offset 0
Count int32 // offset 8
Active bool // offset 12
Ready bool // offset 13
Admin bool // offset 14, then 1 byte tail padding
}
// Empty is zero-sized; a zero-size final field still gets padding so that
// &s.End never points past the struct.
type Empty struct{}
// EndsWithEmpty shows that rule: Sizeof is 16, not 8.
type EndsWithEmpty struct {
N int64
End Empty
}package layout
import (
"testing"
"unsafe"
)
func TestSizes(t *testing.T) {
if unsafe.Sizeof(uintptr(0)) != 8 {
t.Skip("numbers below are for 64-bit platforms")
}
var l Loose
var ti Tight
cases := []struct {
name string
got, want uintptr
}{
{"Sizeof(Loose)", unsafe.Sizeof(l), 32},
{"Sizeof(Tight)", unsafe.Sizeof(ti), 16},
{"Alignof(Loose)", unsafe.Alignof(l), 8},
{"Offsetof(Loose.ID)", unsafe.Offsetof(l.ID), 8},
{"Offsetof(Loose.Count)", unsafe.Offsetof(l.Count), 20},
{"Offsetof(Loose.Admin)", unsafe.Offsetof(l.Admin), 24},
{"Offsetof(Tight.Admin)", unsafe.Offsetof(ti.Admin), 14},
{"Sizeof(Empty)", unsafe.Sizeof(Empty{}), 0},
{"Sizeof(EndsWithEmpty)", unsafe.Sizeof(EndsWithEmpty{}), 16},
}
for _, c := range cases {
if c.got != c.want {
t.Errorf("%s = %d, want %d", c.name, c.got, c.want)
}
}
}
func BenchmarkSliceLoose(b *testing.B) {
s := make([]Loose, 1<<22)
for b.Loop() {
var n int64
for i := range s {
n += s[i].ID
}
_ = n
}
}
func BenchmarkSliceTight(b *testing.B) {
s := make([]Tight, 1<<22)
for b.Loop() {
var n int64
for i := range s {
n += s[i].ID
}
_ = n
}
}Stringer, redaction and immutable values
// Package stringer shows fmt.Stringer, GoStringer, redacting secrets in
// String, and an immutable value type with With* methods.
package stringer
import (
"fmt"
"slices"
"strings"
)
// Credentials must never reach a log line in clear text.
type Credentials struct {
User string
Password string
}
// String has a value receiver, so both Credentials and *Credentials
// print redacted. %v, %s, Println and slog's text output all use it.
func (c Credentials) String() string { return c.User + ":***" }
// GoString covers %#v, which bypasses String.
func (c Credentials) GoString() string {
return fmt.Sprintf("Credentials{User:%q, Password:\"***\"}", c.User)
}
// Status is an enum-like type with a String method.
type Status int
const (
Pending Status = iota
Paid
Shipped
)
func (s Status) String() string {
switch s {
case Pending:
return "pending"
case Paid:
return "paid"
case Shipped:
return "shipped"
}
return fmt.Sprintf("Status(%d)", int(s))
}
// Order is immutable by convention: unexported fields, value receivers,
// and every change returns a new Order. The slice is copied on the way in
// and out, because a shared backing array would break immutability.
type Order struct {
id string
status Status
lines []string
}
// NewOrder copies the caller's slice.
func NewOrder(id string, lines []string) Order {
return Order{id: id, status: Pending, lines: slices.Clone(lines)}
}
// WithStatus returns a copy with a new status; o is unchanged.
func (o Order) WithStatus(s Status) Order {
o.status = s // o is already a copy (value receiver)
return o
}
// WithLine returns a copy with one more line, never sharing the array.
func (o Order) WithLine(l string) Order {
o.lines = append(slices.Clip(o.lines), l) // Clip forces append to allocate
return o
}
// Lines returns a copy so callers cannot mutate the order's state.
func (o Order) Lines() []string { return slices.Clone(o.lines) }
// Status is a getter named after the field, without Get.
func (o Order) Status() Status { return o.status }
func (o Order) String() string {
return fmt.Sprintf("order %s [%s] %s", o.id, o.status, strings.Join(o.lines, ","))
}package stringer
import (
"fmt"
"testing"
)
func TestRedaction(t *testing.T) {
c := Credentials{User: "app", Password: "hunter2"}
for _, got := range []string{
fmt.Sprint(c), fmt.Sprintf("%v", &c), fmt.Sprintf("%s", c), fmt.Sprintf("%+v", c), fmt.Sprintf("%#v", c),
} {
if got != "app:***" && got != `Credentials{User:"app", Password:"***"}` {
t.Fatalf("leaked: %q", got)
}
}
}
func TestStatusString(t *testing.T) {
if got := fmt.Sprint(Paid, Status(9)); got != "paid Status(9)" {
t.Fatalf("got %q", got)
}
}
func TestImmutableOrder(t *testing.T) {
in := []string{"book"}
o1 := NewOrder("o-1", in)
in[0] = "changed by caller"
o2 := o1.WithStatus(Paid).WithLine("pen")
o3 := o1.WithLine("mug")
if got := o1.String(); got != "order o-1 [pending] book" {
t.Fatalf("o1 changed: %q", got)
}
if got := o2.String(); got != "order o-1 [paid] book,pen" {
t.Fatalf("o2 = %q", got)
}
if got := o3.String(); got != "order o-1 [pending] book,mug" {
t.Fatalf("o3 = %q (shared backing array?)", got)
}
o2.Lines()[0] = "tampered"
if o2.Lines()[0] != "book" {
t.Fatal("Lines must return a copy")
}
}Equality and slices of structs
// Package equality compares structs with ==, an Equal method,
// reflect.DeepEqual, and shows copying in slices of structs.
package equality
import (
"slices"
"time"
)
// Event holds a time.Time, which must be compared with Equal, not ==:
// == also compares the monotonic reading and the *Location pointer.
type Event struct {
Name string
At time.Time
}
// Equal is the method go-cmp's cmp.Equal calls when it exists.
func (e Event) Equal(o Event) bool { return e.Name == o.Name && e.At.Equal(o.At) }
// Cart contains a slice, so it is not comparable with ==.
type Cart struct {
ID int
Items []Item
}
// Item is comparable.
type Item struct {
SKU string
Qty int
}
// EqualCarts is the explicit, fast and type-safe comparison.
func EqualCarts(a, b Cart) bool {
return a.ID == b.ID && slices.Equal(a.Items, b.Items)
}
// BumpQtyRange is the classic bug: v is a copy of each element.
func BumpQtyRange(items []Item) {
for _, v := range items {
v.Qty++ //nolint:staticcheck,ineffassign // deliberate: lost update
_ = v
}
}
// BumpQtyIndex mutates the elements in place.
func BumpQtyIndex(items []Item) {
for i := range items {
items[i].Qty++
}
}
// FirstPtr shows the aliasing hazard: a pointer into a slice of structs
// stops tracking the slice once append reallocates.
func FirstPtr(items []Item) (*Item, []Item) {
p := &items[0]
items = append(items, Item{SKU: "new"}) // may move the backing array
return p, items
}package equality
import (
"reflect"
"testing"
"time"
)
func TestTimeInStructs(t *testing.T) {
now := time.Now() // carries a monotonic clock reading
a := Event{"deploy", now}
b := Event{"deploy", now.Round(0)} // Round(0) strips the monotonic reading
if a == b {
t.Fatal("== compares the monotonic reading; expected false")
}
if !a.Equal(b) {
t.Fatal("Equal must ignore the monotonic reading")
}
if reflect.DeepEqual(a, b) {
t.Fatal("DeepEqual compares unexported fields of time.Time too; expected false")
}
}
func TestCarts(t *testing.T) {
a := Cart{1, []Item{{"A", 1}}}
b := Cart{1, []Item{{"A", 1}}}
if !EqualCarts(a, b) || !reflect.DeepEqual(a, b) {
t.Fatal("carts with equal items must be equal")
}
// DeepEqual distinguishes a nil slice from an empty one.
if reflect.DeepEqual(Cart{ID: 1}, Cart{ID: 1, Items: []Item{}}) {
t.Fatal("DeepEqual(nil slice, empty slice) should be false")
}
if !EqualCarts(Cart{ID: 1}, Cart{ID: 1, Items: []Item{}}) {
t.Fatal("slices.Equal treats nil and empty as equal")
}
}
func TestRangeCopies(t *testing.T) {
items := []Item{{"A", 1}, {"B", 1}}
BumpQtyRange(items)
if items[0].Qty != 1 {
t.Fatal("range value is a copy; the slice must be unchanged")
}
BumpQtyIndex(items)
if items[0].Qty != 2 || items[1].Qty != 2 {
t.Fatalf("got %+v", items)
}
}
func TestPointerIntoSlice(t *testing.T) {
items := make([]Item, 1, 1) // full: the next append must reallocate
items[0] = Item{"A", 1}
p, items := FirstPtr(items)
p.Qty = 99
if items[0].Qty == 99 {
t.Fatal("after reallocation p points at the OLD array")
}
}With go-cmp in a test (not a dependency of this module):
import "github.com/google/go-cmp/cmp"
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Order mismatch (-want +got):\n%s", diff)
}Generic structs and pointer-method constraints
// Package generic shows generic struct types and the "pointer method"
// constraint that lets generic code call pointer-receiver methods on T.
package generic
import (
"fmt"
"strconv"
"strings"
)
// Page is a generic struct: one definition for every element type.
type Page[T any] struct {
Items []T `json:"items"`
NextCursor string `json:"next_cursor,omitempty"`
}
// Map converts a page; generic methods cannot add type parameters before
// Go 1.27, so this is a function, not a method.
func Map[T, U any](p Page[T], f func(T) U) Page[U] {
out := Page[U]{Items: make([]U, 0, len(p.Items)), NextCursor: p.NextCursor}
for _, it := range p.Items {
out.Items = append(out.Items, f(it))
}
return out
}
// Decoder is implemented by *SKU, not SKU (pointer receiver).
type Decoder interface{ Decode(string) error }
// PtrDecoder says: PT is *T and has Decode. This is the standard trick
// to construct a T and call a pointer method on it inside generic code.
type PtrDecoder[T any] interface {
*T
Decoder
}
// DecodeAll allocates a zero T per input and decodes into it via PT.
func DecodeAll[T any, PT PtrDecoder[T]](in []string) ([]T, error) {
out := make([]T, len(in))
for i, s := range in {
if err := PT(&out[i]).Decode(s); err != nil {
return nil, fmt.Errorf("item %d: %w", i, err)
}
}
return out, nil
}
// SKU is "CODE:qty".
type SKU struct {
Code string
Qty int
}
// Decode has a pointer receiver because it fills the receiver.
func (s *SKU) Decode(v string) error {
code, qty, ok := strings.Cut(v, ":")
if !ok {
return fmt.Errorf("decode %q: missing ':'", v)
}
n, err := strconv.Atoi(qty)
if err != nil {
return fmt.Errorf("decode %q: %w", v, err)
}
s.Code, s.Qty = code, n
return nil
}package generic
import "testing"
func TestDecodeAll(t *testing.T) {
got, err := DecodeAll[SKU]([]string{"A:1", "B:2"}) // PT is inferred as *SKU
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[1] != (SKU{"B", 2}) {
t.Fatalf("got %+v", got)
}
if _, err := DecodeAll[SKU]([]string{"bad"}); err == nil || err.Error() != `item 0: decode "bad": missing ':'` {
t.Fatalf("err = %v", err)
}
}
func TestMapPage(t *testing.T) {
p := Page[SKU]{Items: []SKU{{"A", 1}, {"B", 2}}, NextCursor: "c2"}
codes := Map(p, func(s SKU) string { return s.Code })
if len(codes.Items) != 2 || codes.Items[1] != "B" || codes.NextCursor != "c2" {
t.Fatalf("got %+v", codes)
}
}Pinning compiler messages in tests
// Package compileerrs type-checks small programs with go/types and returns
// the first error, so tests can pin the exact compiler wording for struct
// and method mistakes without keeping broken files in the module.
package compileerrs
import (
"go/ast"
"go/parser"
"go/token"
"go/types"
)
// Check type-checks one file of package main and returns all errors.
func Check(src string) []string {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "main.go", src, 0)
if err != nil {
return []string{err.Error()}
}
var errs []string
conf := types.Config{
GoVersion: "go1.24",
Error: func(err error) { errs = append(errs, err.(types.Error).Msg) },
}
_, _ = conf.Check("main", fset, []*ast.File{f}, nil)
return errs
}package compileerrs
import (
"strings"
"testing"
)
const prelude = `package main
type Stringer interface{ String() string }
type Counter struct{ n int }
func (c *Counter) Inc() { c.n++ }
func (c *Counter) String() string { return "" }
type A struct{}
func (A) Close() error { return nil }
type B struct{}
func (B) Close() error { return nil }
type C struct { A; B }
type P struct{ X, Y, Z int }
type Order struct { ID int; Lines []string }
type Base struct{ ID int }
type User struct { Base; Name string }
`
func TestCompilerMessages(t *testing.T) {
cases := []struct {
name, body, want string
}{
{"ambiguous selector", `func main() { var c C; _ = c.Close() }`,
"ambiguous selector c.Close"},
{"method set", `func main() { var s Stringer = Counter{}; _ = s }`,
"Counter does not implement Stringer (method String has pointer receiver)"},
{"map element not addressable", `func main() { m := map[string]Counter{}; m["a"].Inc() }`,
"cannot call pointer method Inc on Counter"},
{"assign to field in map", `func main() { m := map[string]Counter{}; m["a"].n = 1 }`,
`cannot assign to struct field m["a"].n in map`},
{"too few positional values", `func main() { _ = P{1, 2} }`,
"too few values in struct literal of type P"},
{"mixed keyed and positional", `func main() { _ = P{X: 1, 2, 3} }`,
"mixture of field:value and value elements in struct literal"},
{"not comparable", `func main() { a, b := Order{}, Order{}; _ = a == b }`,
"invalid operation: a == b (struct containing []string cannot be compared)"},
{"promoted key before 1.27", `func main() { _ = User{ID: 1} }`,
"use of promoted field Base.ID in struct literal of type User requires go1.27 or later"},
{"recursive struct", `type Node struct { Next Node }; func main() {}`,
"invalid recursive type"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
errs := Check(prelude + tc.body)
if len(errs) == 0 {
t.Fatal("expected a compile error")
}
if !strings.Contains(strings.Join(errs, "\n"), tc.want) {
t.Fatalf("errors:\n%s\nwant substring %q", strings.Join(errs, "\n"), tc.want)
}
})
}
}
func TestValidProgram(t *testing.T) {
if errs := Check(prelude + `func main() { var s Stringer = &Counter{}; c := C{}; _ = c.A.Close(); _, _ = s, P{X: 1} }`); len(errs) != 0 {
t.Fatalf("unexpected errors: %v", errs)
}
}Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Small value (money, coordinates, IDs, enums) | Value receivers, NewX returns T | Equal, String, With methods | Copies are cheap and safe across goroutines |
| Entity with identity and state (cart, account, session) | Pointer receivers, NewX returns *T | Unexported fields, validation | One instance, mutated in place |
| Struct with a mutex or other sync field | Pointer receivers, unexported mu | vet copylocks, -race | Locks must not be copied or exposed |
| Plain data (DTO, config, row) | Exported fields, no constructor | Tags, keyed literals | Nothing to protect |
| Library constructor with many settings | Functional options | Defaults first, validate in options | Grows without breaking callers |
| Application wiring from env/files | Config struct | Pointer fields for "unset" | Easy to load and print |
| Reuse a type's fields and API | Embed by value | Explicit methods to resolve conflicts | Promotion without forwarding code |
| Reuse but hide the inner API | Named field | Forwarding methods for what you expose | Encapsulation |
| Override one method of a dependency | Embed the interface | Require it in the constructor | Minimal decorator |
| "Base class with hooks" | Interface or func field for the hook | Constructor injection | Go has no virtual dispatch |
| Millions of instances | Reorder fields; []T | unsafe.Sizeof test, fieldalignment | Memory and cache locality |
| Wire contract | Separate DTO with tags | Golden JSON tests | Domain types keep unexported fields |
For PHP/Laravel developers
| PHP 8.x / Laravel | Go |
|---|---|
class Order { ... } with methods inside | type Order struct { ... } with methods declared beside it |
new Order(...) / __construct | NewOrder(...) function; zero value Order{} always exists |
| Constructor property promotion | Keyed literal Order{ID: id} or NewOrder |
extends | No equivalent; embedding for reuse, interfaces for substitutability |
trait (methods copied into the class; class methods override trait methods) | Embedding (methods forwarded to an inner value; outer methods shadow) |
Trait conflict: fatal error unless insteadof | Embedding conflict: ambiguous selector only when used; resolve with an outer method |
$this inside a trait method refers to the using class | Receiver of a promoted method is the inner value |
readonly property (PHP 8.1) | Unexported field + getter + no mutators |
public/protected/private | Exported/unexported per package; no protected |
__toString() | String() string (fmt.Stringer) |
#[Hidden(['password'])] on an Eloquent model (Laravel 13) | json:"-" tag on the field |
| Objects passed by handle (shared) | Structs copied unless you pass a pointer |
== / === on objects | == only for comparable structs; Equal method otherwise |
PHP's manual describes traits as "a mechanism for code reuse in single inheritance languages", and its precedence rule is "members from the current class override Trait methods, which in turn override inherited methods". That looks like Go's shadowing, with one difference that matters: a trait's methods are copied into the class, so $this->sound() inside a trait method calls the class's sound(). A promoted Go method keeps the inner receiver. On readonly: "As of PHP 8.1.0, a property can be declared with the readonly modifier, which prevents modification of the property after initialization." Go has no field-level equivalent; the immutability conventions give the same guarantee at package level.
<?php
trait Describes
{
public function describe(): string
{
return $this->name . ' says ' . $this->sound(); // late-bound: calls Dog::sound()
}
public function sound(): string { return '...'; }
}
final class Dog
{
use Describes;
public function __construct(public readonly string $name) {}
public function sound(): string { return 'woof'; } // class method overrides the trait method
}
echo (new Dog('Rex'))->describe(); // "Rex says woof" -- the Go embedding version prints "Rex says ..."In architecture: from a single process to a distributed system
Structs are where the domain meets the wire and the database. The same User type tends to be asked to be a domain entity, a JSON response and a table row at once; the architecture question is when to split it. The running example is a shop's User and Order.
Monolith: one process, one database
Simple: one User struct with json and db tags serves the handler, the repository and the template. That is fine while the API and the table evolve together. The table the tags mapper targets:
CREATE TABLE users (
id bigserial PRIMARY KEY,
email text NOT NULL UNIQUE,
name text NOT NULL DEFAULT '',
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- generated by tags.InsertSQL("users", &u):
INSERT INTO users (email, name, password_hash, created_at) VALUES ($1, $2, $3, $4) RETURNING id;Complex: the first leak is a field added to the table and the struct, which appears in every JSON response unless it is tagged json:"-". Rows are scanned with database/sql & pgx, which match columns by position or name, not by tags.
Modular monolith and multiple databases
Package boundaries become the encapsulation boundary. A module exports a constructor and methods, not fields: orders.NewOrder(...) with unexported fields, so another module cannot set status to "shipped" without going through Ship(). Modules exchange small value types or DTOs, not each other's entities; embedding another module's struct couples you to every field and method it will ever add (and to new ambiguous selector errors). The decorator pattern with an embedded interface is how cross-cutting concerns (metrics, caching, tracing) wrap a module's repository without touching it.
Microservices
Structs become wire contracts, and the rules change: the receiver of your JSON may be a different version of your code.
1 orders v2 adds Discount int `json:"discount,omitempty"` to OrderDTO
2 orders -> POST /payments {"id":"o-1","total":1999,"discount":200}
3 payments v1 decodes into its OrderDTO: unknown "discount" ignored by default
4 payments v1 -> event OrderPaid {"id":"o-1","total":1999} discount lost downstream
5 fix: DisallowUnknownFields in strict consumers, versioned schemas, contract testsomitempty drops 0 and "", which may be meaningful values; omitzero (Go 1.24) also drops zero time.Time and zero structs, and honours an IsZero() method. Keep DTOs as separate structs from domain types, map them explicitly, and pin the JSON with golden tests. For Protobuf, the generated structs are the contract; see gRPC & Protobuf in Go. Service-level contract design is in API Versioning & Evolution.
Distributed data: caches, events and replicas
Structs serialised into Redis, Kafka or an outbox table live longer than the code that wrote them. A field renamed in Go but not in its tag keeps compatibility; a tag renamed breaks every cached or queued value. Adding a field is safe when its zero value means "unknown"; removing one is safe when readers ignore unknown keys. Equality across versions must be semantic (Equal), not ==, because a new field makes old and new values unequal. Immutable value structs are safe to share across goroutines that read replicated or cached data; mutable entities need a lock or a copy per reader. Message design is covered in Message Design & Schema Evolution.
Scaling path: 1×, 10×, 100×
| Load | What matters about structs | Change |
|---|---|---|
| 1× (one service) | Correctness: receivers, constructors, tags | Keyed literals, vet in CI, DTO/domain split when the API stabilises |
| 10× (many instances, caches) | Serialisation cost and compatibility | Golden tests, omitzero, avoid reflection-heavy mappers on hot paths |
| 100× (millions of values in memory, high allocation rates) | Size and pointer density | Reorder fields, []T over []*T, fewer pointer fields, sync.Pool for large temporary structs, measure with unsafe.Sizeof and pprof |
Lab
Everything runs on the host with Go only; no containers. Steps 1–5 were run with Go 1.27.4 on darwin/arm64 (Apple M4 Pro) and the output below is real; step 6 needs a download and is "expected, not run".
1. Run the module's tests (race detector on).
cd docs/snippets/go/structs-methods-embedding/go
gofmt -l . && go vet ./... && go test -race ./...
# ok academy/structs-methods-embedding/compileerrs 1.337s
# ok academy/structs-methods-embedding/constructors 1.302s
# ok academy/structs-methods-embedding/embedding 1.302s
# ... (11 packages, all ok)2. See the compiler errors. Put each snippet from the error table in its own main.go under a scratch module with go 1.24 and build:
go build ./ambig # ambig/main.go:18:8: ambiguous selector c.Close
go build ./methodset # ... Counter does not implement fmt.Stringer (method String has pointer receiver)
go build ./mapelem # cannot call pointer method Inc on Counter / cannot assign to struct field m["a"].n in map
go build ./compare # invalid operation: a == b (struct containing []string cannot be compared) / invalid map key type Order
go build ./promokey # use of promoted field Base.ID in struct literal of type User requires go1.27 or later (-lang was set to go1.24; check go.mod)3. Let vet find the silent bugs.
go vet ./unkeyedvet
# unkeyedvet/main.go:22:10: net.DNSConfigError struct literal uses unkeyed fields
# unkeyedvet/main.go:14:9: Balance passes lock by value: errs/unkeyedvet.Account contains sync.Mutex
# unkeyedvet/main.go:25:7: assignment copies lock value to b: errs/unkeyedvet.Account contains sync.Mutex
# unkeyedvet/main.go:17:2: struct field tag `json:name` not compatible with reflect.StructTag.Get: bad syntax for struct tag value
# unkeyedvet/main.go:18:2: struct field age has json tag but is not exported4. A nil embedded pointer.
go run ./nilembed
# panic: runtime error: invalid memory address or nil pointer dereference
# [signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x1027cf5b0]
# goroutine 1 [running]:
# main.(*Logger).Log(...)5. Padding at scale.
go test -run '^$' -bench . -benchmem ./layout
# cpu: Apple M4 Pro
# BenchmarkSliceLoose-12 246 4983600 ns/op 0 B/op 0 allocs/op
# BenchmarkSliceTight-12 333 3868072 ns/op 0 B/op 0 allocs/opWith 4 194 304 elements the loose layout is 128 MiB and the tight one 64 MiB; the scan is about 22 % faster. With 65 536 elements (2 MiB vs 1 MiB, cache-resident) the same benchmark measured 76.3 µs vs 75.1 µs: padding is a memory problem first.
6. fieldalignment (expected, not run).
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
fieldalignment ./layout
# layout.go:5:12: struct of size 32 could be 16 (older x/tools wording)
# current x/tools source formats it as "... has size 32 ... but the optimal size is 16 ..."
fieldalignment -fix ./layout # rewrites the field order; review comments afterwards7. Go 1.27 features (run in a module with go 1.27). A promoted-field key User{ID: 1, Name: "a"}, a generic method func (b *Bag) Filter[T any]() []T, and new(42) compiled and printed 1 [1 2] and 42.
Common misconceptions
| Belief | Reality |
|---|---|
| Embedding is inheritance | It is a field plus promoted selectors; no subtype relation, no virtual dispatch |
| An "overriding" method on the outer type is called by the inner type's methods | Inner methods always call inner methods; use an interface |
| Value receivers are safer | They copy; mutations are lost and copies of locks break |
| Mixing value and pointer receivers is fine | T and *T then satisfy different interfaces; CodeReviewComments says don't mix |
If c.M() compiles, c implements the interface with M | Auto & applies to calls on addressable values, not to interface satisfaction |
| A nil pointer receiver always panics | Only when the method dereferences it |
| Every type needs a constructor | Prefer useful zero values; NewX only for invariants and dependencies |
| Struct tags are checked by the compiler | They are strings; only go vet checks the syntax |
json tags work on unexported fields | Unexported fields are skipped; vet warns |
reflect.DeepEqual is a better == | It compares unexported fields, nil vs empty, and is slow; tests only |
for _, v := range lets me edit elements | v is a copy; use the index |
Embedding sync.Mutex is the idiom | It exports Lock/Unlock; use an unexported mu field |
| Field order does not matter | It changes size through padding |
Getters should be called GetX | X(); setters SetX |
Cheat sheet
| Topic | Remember |
|---|---|
| Literals | Keyed by default; positional only for small local types; vet composites |
| Comparable | All fields comparable → == and map keys; slices/maps/funcs block it |
| Zero value | Design it to work: mutex, buffer, lazily made map, nil func = default |
| Constructor | NewX, validate, return T for values and *T for stateful types, plus error |
| Options | type Option func(*T) error; defaults first, then options, then validation |
| Receiver | Mutates, has a lock, large, or siblings use *T → *T; small immutable → T |
| Method sets | T ⊂ *T; interface satisfaction uses them; var _ I = (*T)(nil) |
| Addressable | Variables, *p, s[i], fields of addressable structs; not m[k], not f() |
| Embedding | Field named after the type; shallowest depth wins; same depth → ambiguous when used |
| No virtual dispatch | Promoted methods keep the inner receiver; interfaces dispatch |
| Embedded interface | Decorator: override one method, forward the rest; nil inner panics |
| Mutex | mu sync.Mutex unexported, pointer receivers, never copy; vet copylocks |
| Tags | key:"value" pairs, space-separated; Get/Lookup; vet structtag |
| JSON | Exported fields only; -, omitempty, omitzero; decode into a pointer |
| Padding | Largest alignment first for many instances; unsafe.Sizeof test |
| Equality | == exact, Equal semantic, cmp.Diff in tests, t.Equal(u) for time |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — fmt.Println(c) prints {hits 3} but fmt.Println(&c) prints hits=3. Why? Important
Answer
Answer: String has a pointer receiver, so it is in the method set of *Counter only. fmt checks whether the value it receives implements fmt.Stringer; a Counter value does not, so it prints the fields. See Method sets.
2 — Why does m["a"].Inc() not compile when s[0].Inc() does? Must-know
Answer
Answer: Inc needs *Counter. A slice element is addressable, so the compiler rewrites the call to (&s[0]).Inc(). A map element is not addressable (maps move entries), so there is no pointer to take: cannot call pointer method Inc on Counter. Use map[string]*Counter or copy out and write back.
3 — Dog embeds Animal and declares Sound(). Animal.Describe() calls a.Sound(). What does d.Describe() return and why? Important
Answer
Answer: It uses Animal.Sound, because d.Describe() is d.Animal.Describe() and its receiver is the Animal; concrete method calls are resolved statically. To get Dog.Sound, pass the dog as an interface (Speaker) to the code that needs the varying behaviour.
4 — A struct embeds A and B, both with Close(). Does it compile? Must-know
Answer
Answer: The declaration compiles. Calling x.Close() fails with ambiguous selector x.Close. Resolve it with explicit paths (x.A.Close()) or by declaring Close on the outer type.
5 — Why should a struct containing sync.Mutex have only pointer receivers? Must-know
Answer
Answer: A value receiver copies the struct, including the mutex; the copy's lock state is unrelated to the original, so locking it protects nothing, and a copy of a locked mutex is locked forever. vet's copylocks reports passes lock by value.
6 — json:name is on a field and the JSON key is still Name. What happened and what would have caught it? Must-know
Answer
Answer: The value must be quoted: json:"name". A malformed tag is just a string, so Tag.Get("json") returns "" and the default key is used. go vet's structtag check reports bad syntax for struct tag value.
7 — When should NewX return a value instead of a pointer? Important
Answer
Answer: When X is a small value type with value receivers (money, coordinates, time.Time-like types). Return a pointer for stateful or large types, types with locks, and types whose methods use pointer receivers.
8 — Two Event structs hold the same instant but == says they differ. Why, and what should you use? Must-know
Answer
Answer: time.Time contains a monotonic clock reading and a location pointer; == compares those too. Use an Equal method that calls t.Equal(u), or strip the monotonic reading with Round(0) before storing.
9 — How do you write a generic DecodeAll[T] that calls a pointer-receiver Decode on each new element? Good to know
Answer
Answer: Add a second type parameter constrained to interface{ *T; Decoder }, allocate []T, and call PT(&out[i]).Decode(s). Callers write DecodeAll[SKU](in); PT is inferred as *SKU.
10 — Reordering a struct's fields halved its size. When is that worth doing, and when not? Important
Answer
Answer: Worth it for types with many instances (large slices, caches) where memory and cache misses dominate; the lab measured 22 % faster scans at 128 MiB vs 64 MiB, but no difference when the data fits in cache. Not worth it for singletons or where packing would put two goroutines' hot fields on one cache line (false sharing).
Glossary
| Term | Meaning |
|---|---|
| Struct | A composite type: a fixed sequence of named, typed fields |
| Field | One named element of a struct; exported if its name starts upper-case |
| Struct literal / composite literal | An expression that builds a value inline: T{...}, &T{...} |
| Keyed literal | A struct literal with Field: value elements; omitted fields are zero |
| Positional literal | A struct literal listing every field in declaration order |
| Comparable | A type whose values can be compared with == and used as map keys |
| Anonymous struct | A struct type used without a name, e.g. in test tables |
| Empty struct | struct{}, zero bytes; used for sets and signals |
| Zero value | The value a variable has without initialisation; all fields zero |
| Constructor | A function (by convention NewX) that builds a valid value |
| NewX | Naming convention for constructors; New when the package has one main type |
| Functional options | Variadic func(*T) error values applied by a constructor |
| Config struct | A struct of settings whose zero fields mean defaults |
| Method | A function with a receiver, declared on a defined type in the same package |
| Receiver | The parameter before a method's name |
| Value receiver | func (t T) M(); the method gets a copy |
| Pointer receiver | func (t *T) M(); the method can mutate the original |
| Nil receiver | A pointer receiver that is nil; legal until dereferenced |
| Method set | The methods callable on a type and used for interface satisfaction |
| Addressable | An operand you can take the address of: variable, *p, s[i], field of addressable struct |
| Auto address | The compiler rewriting v.M() to (&v).M() for addressable v |
| Method value | x.M without a call; receiver bound and copied |
| Method expression | T.M or (*T).M; receiver becomes the first parameter |
| Embedding | Declaring a field by type only; its fields and methods are promoted |
| Embedded field | The field created by embedding, named after its type |
| Promoted field | An embedded field's field reachable as x.f |
| Promoted method | An embedded field's method in the outer type's method set |
| Shadowing | A shallower field or method hiding a deeper one with the same name |
| Ambiguous selector | Compile error when two candidates exist at the same shallowest depth |
| Embedded interface | An interface type embedded in a struct; its methods forward to the held value |
| Embedded pointer | An embedded *T; zero value is nil |
| Decoration | Wrapping a value to change some methods and forward the rest |
| sync.Mutex embedding | Embedding a mutex, which exports Lock/Unlock; avoid |
| copylocks | vet analyzer reporting copied locks |
| Inheritance | Subtype-plus-reuse relation between classes; Go has none |
| Virtual dispatch | Choosing the method by the runtime type; in Go only through interfaces |
| Struct tag | A string after a field, read by libraries through reflect |
| json tag / db tag | Tag keys read by encoding/json and by SQL mappers |
| reflect.StructTag | The tag's type, with Get and Lookup |
| structtag vet | The vet analyzer checking tag syntax and tags on unexported fields |
| omitempty / omitzero | JSON options that drop empty or zero values (omitzero since Go 1.24) |
| Unexported field | Lower-case field, invisible outside the package and to reflection-based encoders |
| Field alignment | The address multiple a field type requires (unsafe.Alignof) |
| Padding | Unused bytes inserted to satisfy alignment |
| fieldalignment | x/tools analyzer suggesting a field order that reduces size |
| False sharing | Two goroutines' data on one cache line slowing each other |
| Slice of structs | []T: values stored contiguously; range yields copies |
| Getter / setter | Owner() / SetOwner(); no Get prefix |
| Stringer | fmt.Stringer, a type with String() string |
| GoStringer | fmt.GoStringer, used for %#v |
| TextMarshaler | encoding interface for text encoding; unmarshal side uses a pointer receiver |
| DeepEqual | reflect.DeepEqual, recursive comparison including unexported fields |
| go-cmp | github.com/google/go-cmp/cmp, test-time comparison and diffs |
| Immutability | Convention: unexported fields, value receivers, copies on change |
| Value object | A type defined by its values, compared by value, immutable |
| Generic method | A method with its own type parameters (Go 1.27) |
| Trait | PHP mechanism that copies methods into a class |
| Readonly property | PHP 8.1 property that can be initialised once |
References
- Go language: The Go Programming Language Specification (language version go1.27, sections Struct types, Method sets, Composite literals, Selectors, Address operators, Comparison operators), Effective Go (Getters, Constructors and composite literals, Pointers vs. Values, Embedding), Go FAQ (type inheritance, dynamic dispatch, methods on values or pointers, method sets), The Go Memory Model
- Go Wiki: CodeReviewComments (Receiver Names, Receiver Type)
- Release notes: Go 1.20, Go 1.22 release blog, Go 1.24, Go 1.25, Go 1.26, Go 1.27
- Go blog: JSON and Go, The Laws of Reflection
- Standard library source (pkg.go.dev returned 403 to the fetcher; the same doc comments were read from source): reflect/type.go (StructTag), reflect/deepequal.go, encoding/json/encode.go, encoding/json/decode.go, encoding/encoding.go, fmt/print.go (Stringer), sync/mutex.go, unsafe/unsafe.go, cmd/vet/doc.go
- Analyzers (golang.org/x/tools source): fieldalignment, structtag, composite, copylock
- golangci-lint: linter configuration (govet analyzers, fieldalignment)
- go-cmp: repository, cmp/compare.go
- Functional options: Rob Pike, Self-referential functions and the design of options (2014); Dave Cheney, Functional options for friendly APIs (2014)
- PHP and Laravel: PHP Traits, PHP Properties (readonly), Laravel 13 Eloquent Serialization (Hidden attribute)