{"guides":[{"caption":"The zero value comes from the type, not from leftover memory.","id":"core.zero-values","mode":"comparison","nodes":[{"code":"var count int","detail":"Starts at 0","label":"Numbers"},{"code":"var name string","detail":"Starts at \"\"; bool starts at false","label":"Text and flags"},{"code":"var p *int","detail":"Pointers, slices, maps and channels start nil","label":"References"}],"practical":"Design a type so its zero value is useful when possible. A zero counter can be incremented and a nil slice can be appended to. A nil map can be read, but needs allocation before a write; a nil channel blocks both sends and receives.","reference":"https://go.dev/ref/spec","title":"A value exists before you assign one","watchOut":"Zero does not mean ready for every operation. Check the rules of the specific type before using it."},{"caption":"Short declarations are for local variables; package-level declarations use var.","id":"core.short-declaration","mode":"flow","nodes":[{"code":"size := 8","detail":"Creates a name in this block","label":"Declare"},{"code":"size = 12","detail":"Assigns the existing name","label":"Reuse"},{"code":"size, err := read()","detail":"At least one name must be new","label":"Mixed declaration"}],"practical":"Read a short declaration together with its block. Inside a nested if or for block, the same spelling may introduce a different variable. A short declaration with multiple names may reuse names from that same block when at least one other name is new.","reference":"https://go.dev/ref/spec","title":"Creation and reassignment are different steps","watchOut":"An inner `err :=` can shadow an outer `err`. Use `=` when you intend to update an existing variable."},{"caption":"The signature makes the failure path visible at the call site.","id":"core.multiple-returns","mode":"flow","nodes":[{"code":"value, err := load()","detail":"The function returns both","label":"Call"},{"code":"if err != nil","detail":"Handle the failure path","label":"Branch"},{"code":"use(value)","detail":"Use the successful result","label":"Continue"}],"practical":"Keep the failure branch short, then let the successful path continue without extra nesting. Give the error context at the boundary where you know what operation was attempted. A function may return a useful partial result with an error only when its contract explicitly says so.","reference":"https://go.dev/ref/spec","title":"Check the error before using the value","watchOut":"Discarding an error with `_` does not handle it. Make that choice only when the operation is known to be safe."},{"caption":"Go checks unused imports per file and unused local variables at compile time.","id":"core.unused-is-an-error","mode":"comparison","nodes":[{"code":"import \"fmt\"","detail":"A file must use its imports","label":"Import"},{"code":"label := \"go\"","detail":"A declared local must be used","label":"Local variable"},{"code":"_, err := read()","detail":"The blank identifier names no variable","label":"Intentional discard"}],"practical":"During a repair, decide whether the unused value belongs in the result or should be removed. Keep imports close to the code that needs them. The blank identifier is useful for an intentionally ignored result, but removing dead work usually makes the program clearer.","reference":"https://go.dev/ref/spec","title":"Every local name needs a purpose","watchOut":"A blank assignment only satisfies the compiler. It does not explain why calculating an unused value was necessary."},{"caption":"Constant arithmetic is exact until a typed operation imposes a representation.","id":"core.constants","mode":"flow","nodes":[{"code":"const limit = 1 << 40","detail":"No machine-width integer yet","label":"Exact constant"},{"code":"var n int64 = limit","detail":"The value must fit int64","label":"Typed context"},{"code":"const first = iota","detail":"iota advances per ConstSpec","label":"Enumeration"}],"practical":"Use typed constants when a public API needs a particular type; keep untyped constants flexible when callers may use different numeric types. In a const block, iota counts specifications, including a blank-identifier specification. Several names on one specification share the same iota value.","reference":"https://go.dev/ref/spec","title":"A constant gets a type when the context asks","watchOut":"A constant can be valid by itself and still overflow the type of the variable or argument receiving it."},{"caption":"An expressionless switch is a sequence of conditions, not a loop.","id":"core.switch","mode":"flow","nodes":[{"code":"switch {","detail":"Conditions are checked in order","label":"Evaluate"},{"code":"case ready:","detail":"Run the first matching case","label":"Choose"},{"code":"default:","detail":"No implicit fallthrough","label":"Finish"}],"practical":"Put more specific conditions before broader ones. Several values can share one case, so avoid repeating an identical body. A break can explicitly leave a switch early, but no break is needed merely to stop at the end of a case.","reference":"https://go.dev/ref/spec","title":"The first matching case finishes the switch","watchOut":"`fallthrough` runs the next case body without testing its condition. Use it only when that behavior is intentional."},{"caption":"Equal storage widths do not make two numeric types interchangeable.","id":"core.conversions","mode":"flow","nodes":[{"code":"type Meters float64","detail":"A named type protects a meaning","label":"Distinct types"},{"code":"float64(distance)","detail":"Choose a common numeric type","label":"Explicit conversion"},{"code":"sum / float64(count)","detail":"Both operands now agree","label":"Operation"}],"practical":"Choose the result type before choosing a conversion. Converting an integer to a float can lose precision for large values; converting a float to an integer truncates the fractional part. An explicit conversion documents the decision, but it does not make a lossy conversion harmless.","reference":"https://go.dev/ref/spec","title":"Make the type change visible","watchOut":"Check an empty collection before dividing by its length. Type correctness alone does not prevent division by zero."},{"caption":"A bare return returns the current named result values.","id":"core.named-results","mode":"flow","nodes":[{"code":"func split() (a, b int)","detail":"Declares result variables","label":"Signature"},{"code":"a = 2","detail":"Assignments update those variables","label":"Body"},{"code":"return a, b","detail":"Explicit values keep the exit clear","label":"Return"}],"practical":"Use result names when they explain a pair of similar types, such as a lower and upper bound. They begin at their zero values and remain in scope for the body. An explicit return is often easier to review than a bare return once the function has branches.","reference":"https://go.dev/ref/spec","title":"Named results are local variables","watchOut":"A deferred closure can change named results before the caller receives them. That is useful, but deserves a visible contract."},{"caption":"Registration order and execution order point in opposite directions.","id":"core.defer-stack","mode":"stack","nodes":[{"code":"defer closeA()","detail":"Arguments are evaluated now","label":"Register first"},{"code":"defer closeB()","detail":"This call is stacked above A","label":"Register second"},{"code":"closeB(); closeA()","detail":"The newest deferred call runs first","label":"Return"}],"practical":"Put cleanup next to successful acquisition so later return paths cannot bypass it. The function and arguments of a deferred call are evaluated when defer executes; a deferred closure can instead read variables later. This difference explains many surprising loop and mutation examples.","reference":"https://go.dev/ref/spec","title":"Deferred work unwinds in reverse order","watchOut":"Defer runs when the surrounding function returns, not at the end of an inner block or one loop iteration."},{"caption":"A struct value carries its fields together; assigning it copies that value.","id":"structs.literals","mode":"comparison","nodes":[{"code":"type Point struct { X, Y int }","detail":"A fixed set of fields","label":"Type"},{"code":"Point{X: 3}","detail":"Omitted fields receive zero values","label":"Keyed literal"},{"code":"next := point","detail":"Copies the struct value","label":"Copy"}],"practical":"Prefer keyed literals when the field meanings are not obvious. An omitted field is deliberately zero, which is helpful for configuration structs. A struct copy is shallow: slice, map and pointer fields still refer to the same backing data even though the outer struct is a new value.","reference":"https://go.dev/ref/spec","title":"Field names make construction readable","watchOut":"A copied struct containing a mutex must not be used as an independent lock after the original lock has been used."},{"caption":"The receiver is an explicit part of the method declaration.","id":"structs.methods","mode":"flow","nodes":[{"code":"type Counter struct { N int }","detail":"The receiver type owns the method","label":"Value"},{"code":"func (c *Counter) Add()","detail":"A pointer receiver can mutate c","label":"Method"},{"code":"counter.Add()","detail":"The receiver supplies the first operand","label":"Call"}],"practical":"Choose pointer receivers when a method needs to change the receiver or when copying the value would be inappropriate. Keep receiver naming short and consistent across methods. Whether a value satisfies an interface is decided by its method set, which is a separate rule from convenient call syntax.","reference":"https://go.dev/ref/spec","title":"A receiver gives a function a home","watchOut":"Go may take the address of an addressable value for a method call. That convenience does not add pointer methods to its value method set."},{"caption":"Assigning through either pointer changes the one shared value.","id":"structs.pointers","mode":"shared","nodes":[{"code":"count := 4","detail":"The storage being referred to","label":"One value"},{"code":"p := &count","detail":"Refers to count","label":"First pointer"},{"code":"q := p","detail":"Refers to that same count","label":"Second pointer"}],"practical":"Use a pointer to communicate shared identity or a permitted mutation. A pointer is itself copied when passed to a function, so reassigning the parameter changes only that local pointer; assigning through it changes the pointed-to value. Check nil before dereferencing an optional pointer.","reference":"https://go.dev/ref/spec","title":"Two names can reach one value","watchOut":"A pointer does not automatically make code faster. Allocation and copying behavior depend on the program and compiler."},{"caption":"Calls to one returned closure share its captured variables.","id":"structs.closures","mode":"flow","nodes":[{"code":"total := 0","detail":"A captured variable is created","label":"Create"},{"code":"func() { total++ }","detail":"The closure uses that variable","label":"Capture"},{"code":"next()","detail":"It sees the updated total","label":"Call again"}],"practical":"A closure is a useful way to return a small stateful operation without exposing a struct. Separate calls to the factory create separate captured state. Multiple closures created in one environment may share that state, so concurrent use still needs synchronization.","reference":"https://go.dev/ref/spec","title":"The function keeps access to its environment","watchOut":"Capturing a variable does not freeze its current value. Copy it deliberately when the callback needs a snapshot."},{"caption":"Go keeps reachable values alive; a returned pointer is not a dangling reference.","id":"structs.escape","mode":"flow","nodes":[{"code":"item := Item{}","detail":"The function creates a local value","label":"Create"},{"code":"return &item","detail":"The caller may retain it","label":"Return reference"},{"code":"p.Name = \"go\"","detail":"The value remains valid","label":"Use safely"}],"practical":"Escape analysis decides where storage can live while preserving language semantics. Returning a pointer to a local is safe, but it may require heap storage. Prefer the API shape that expresses ownership and optionality clearly, then inspect allocation behavior if a measured hot path needs improvement.","reference":"https://go.dev/ref/spec","title":"The value outlives the returning function","watchOut":"Safe lifetime does not mean synchronized access. Sharing the returned pointer across goroutines still requires coordination."},{"caption":"Length is the current view; capacity is the room available behind that view.","id":"collections.length-capacity","mode":"sequence","nodes":[{"code":"len(s)","detail":"Indices from 0 up to len(s)-1","label":"Visible elements"},{"code":"cap(s)","detail":"The reslicing limit from this start","label":"Reserved storage"},{"code":"s = append(s, v)","detail":"May reuse or replace the backing array","label":"Growth"}],"practical":"Use make with a capacity estimate when building a result incrementally. An append returns the updated slice header, so retain that returned value. The growth policy is an implementation detail; correct code must not depend on a particular capacity after an allocation.","reference":"https://go.dev/ref/spec","title":"A slice sees part of a backing array","watchOut":"Capacity does not permit indexing beyond length. Reslice first when exposing an existing part of the backing array."},{"caption":"Copying a slice copies its header, not its elements.","id":"collections.append-aliasing","mode":"shared","nodes":[{"code":"[1, 2, 3, 4]","detail":"The elements live here","label":"Backing storage"},{"code":"a := data[:2]","detail":"Has its own length and capacity","label":"View A"},{"code":"b := data[1:3]","detail":"Overlapping elements refer to the same storage","label":"View B"}],"practical":"Decide whether a function returns a view or an independent copy. Use copy or slices.Clone when callers must not share mutations. A full slice expression can restrict capacity and force a later append to allocate, but it does not detach elements already visible in the slice.","reference":"https://go.dev/ref/spec","title":"Slice headers can share one backing array","watchOut":"An append that fits capacity may overwrite values visible through another slice. An append that reallocates has different sharing behavior."},{"caption":"A safe read does not imply that a map is allocated for writes.","id":"collections.map-zero-value","mode":"comparison","nodes":[{"code":"var m map[string]int","detail":"Reads return the value type zero","label":"Nil map"},{"code":"m[\"missing\"]","detail":"Also returns zero","label":"Absent key"},{"code":"m = make(map[string]int)","detail":"Writes are now permitted","label":"Allocated map"}],"practical":"Initialize a map at the point where a function takes responsibility for storing entries. Use the two-result lookup when an absent key must be distinguished from a stored zero. Deleting a key from a nil map is safe, but assignment to a nil map panics.","reference":"https://go.dev/ref/spec","title":"Reading and writing have different requirements","watchOut":"Maps are not safe for unsynchronized concurrent reads and writes. Protect access or transfer ownership."},{"caption":"A rune is a code point; a user-visible character may contain several runes.","id":"collections.runes-not-bytes","mode":"comparison","nodes":[{"code":"len(\"é\") == 2","detail":"Length counts bytes","label":"UTF-8 bytes"},{"code":"for _, r := range text","detail":"range decodes Unicode code points","label":"Rune iteration"},{"code":"text[i]","detail":"Indexing returns one byte","label":"Byte index"}],"practical":"Choose the unit the operation actually needs. Protocols often need byte offsets; Unicode processing often needs runes. Range over a string yields the byte offset and the decoded rune, so its indexes are not a consecutive rune counter.","reference":"https://go.dev/ref/spec","title":"Bytes and Unicode code points are different views","watchOut":"Counting runes is still not counting displayed characters. Combining marks and emoji sequences can contain multiple code points."},{"caption":"The range loop and yield call cooperate to stop at the same boundary.","id":"collections.iterators","mode":"flow","nodes":[{"code":"func(yield func(int) bool)","detail":"The iterator supplies each value","label":"Producer"},{"code":"for v := range values","detail":"The loop body receives it","label":"Consumer"},{"code":"if !yield(v) { return }","detail":"A false result ends production","label":"Stop signal"}],"practical":"Keep iterator state local unless reuse is intentionally stateful. A rangeable function may yield no values, one value, or a key and value, according to its signature. As soon as yield returns false, stop calling it and release any resources owned by the iterator.","reference":"https://pkg.go.dev/iter","title":"The iterator offers values through yield","watchOut":"Calling yield again after it returned false violates the iterator protocol and can panic."},{"caption":"Both operations are checked; capacity is not an indexing permission.","id":"collections.bounds","mode":"comparison","nodes":[{"code":"s[i]","detail":"Requires 0 ≤ i < len(s)","label":"Index"},{"code":"s[:n]","detail":"May extend up to cap(s)","label":"Reslice"},{"code":"s[:n:n]","detail":"Also limits future append capacity","label":"Full slice"}],"practical":"Check bounds at the boundary where external indexes enter your program. A sub-slice capacity starts at its own first element, not at the original array beginning. A full slice expression is useful when passing a view to code that may append without permission to overwrite later elements.","reference":"https://go.dev/ref/spec","title":"Indexing and reslicing use different limits","watchOut":"Restricting capacity prevents append from using later storage; it does not prevent writes to elements already in the view."},{"caption":"The language does not specify map iteration order.","id":"collections.map-order","mode":"flow","nodes":[{"code":"map[string]int","detail":"Stores associations, not an order","label":"Map"},{"code":"keys = append(keys, key)","detail":"Extract the keys","label":"Collect"},{"code":"slices.Sort(keys)","detail":"Produce deterministic output","label":"Sort then read"}],"practical":"Use sorted keys for reports, snapshots, stable tests and serialized text. Test membership independently of order when order is irrelevant. An iteration may use a different order on the next pass; seeing one repeated order in a small example does not establish a guarantee.","reference":"https://go.dev/ref/spec","title":"Sort keys when output order matters","watchOut":"Do not describe map traversal as insertion order or rely on a particular random distribution."},{"caption":"A builder avoids repeatedly concatenating an ever-growing prefix.","id":"collections.strings-builder","mode":"flow","nodes":[{"code":"var b strings.Builder","detail":"The zero value is ready","label":"Builder"},{"code":"b.WriteString(part)","detail":"Grow the accumulated buffer","label":"Append"},{"code":"result := b.String()","detail":"Read the completed string","label":"Finish"}],"practical":"Use strings.Join when all pieces are already collected; use strings.Builder when generating text step by step. Grow can reserve a known size, but it is optional. A builder is for text, while bytes.Buffer is useful when both byte-oriented reads and writes are needed.","reference":"https://pkg.go.dev/strings#Builder","title":"Accumulate bytes before producing the string","watchOut":"Do not copy a non-zero strings.Builder. Keep one owner and measure before adding speculative capacity estimates."},{"caption":"make returns a slice, map or channel; new returns a pointer.","id":"collections.make-and-new","mode":"comparison","nodes":[{"code":"make([]int, 3)","detail":"A usable slice with three zero elements","label":"Slice"},{"code":"make(map[string]int)","detail":"Initializes runtime storage","label":"Map or channel"},{"code":"new(int)","detail":"Returns a pointer to a zero int","label":"Pointer"}],"practical":"Pick the form that matches the value your API needs. A struct literal often expresses initialization more clearly than new. A pointer to a nil map is still a pointer to a nil map: allocating the pointer does not initialize the map it points to.","reference":"https://go.dev/ref/spec","title":"Allocation and initialization answer different questions","watchOut":"`new([]int)` yields a pointer to a nil slice. It does not allocate any slice elements."},{"caption":"Arrays are values; slices describe a view over elements.","id":"collections.arrays","mode":"comparison","nodes":[{"code":"[3]int","detail":"Exactly three elements","label":"Fixed value"},{"code":"[4]int","detail":"Not assignable as [3]int","label":"Different type"},{"code":"[]int","detail":"A slice refers to backing storage","label":"Flexible view"}],"practical":"Use arrays when a fixed length is part of the contract, such as a digest. Array assignment copies every element. Slicing an array creates a view of it; converting or copying into another array is a separate operation with its own bounds requirements.","reference":"https://go.dev/ref/spec","title":"Array length belongs to its type","watchOut":"Passing an array by value copies it. A slice parameter does not copy its backing elements."},{"caption":"The boolean answers whether the key exists, independently of the value.","id":"collections.map-ok","mode":"comparison","nodes":[{"code":"m[\"known\"] = 0","detail":"value is 0; ok is true","label":"Stored zero"},{"code":"v, ok := m[\"absent\"]","detail":"value is 0; ok is false","label":"Absent entry"},{"code":"if !ok { ... }","detail":"Handle absence explicitly","label":"Decision"}],"practical":"Use comma-ok when zero is a meaningful stored value. The same pattern appears in type assertions and channel receives, but the boolean answers a different presence question in each case. Give it a name such as found when that improves the branch.","reference":"https://go.dev/ref/spec","title":"Presence is a second result","watchOut":"Testing `v == 0` cannot distinguish an absent key from an entry explicitly containing zero."},{"caption":"Nil and empty slices behave alike for length, range and append.","id":"collections.nil-slice","mode":"flow","nodes":[{"code":"var values []int","detail":"Length and capacity are zero","label":"Start"},{"code":"values = append(values, 9)","detail":"Append allocates when needed","label":"Grow"},{"code":"range values","detail":"An empty slice runs zero iterations","label":"Use"}],"practical":"Return a nil slice when no results is a natural zero value, unless the API requires a non-nil empty value. Most callers should inspect length rather than compare to nil. Encoders may distinguish the two representations, so document the serialized contract when it matters.","reference":"https://go.dev/ref/spec","title":"A nil slice already supports empty operations","watchOut":"The standard encoding/json package encodes a nil slice as null and a non-nil empty slice as []."},{"caption":"Named functions and closures can satisfy the same function type.","id":"collections.function-values","mode":"flow","nodes":[{"code":"func(int) bool","detail":"Names the input and output types","label":"Function value"},{"code":"keep func(int) bool","detail":"Accepts any matching function","label":"Parameter"},{"code":"keep(value)","detail":"Calls the supplied behavior","label":"Invocation"}],"practical":"Pass a function when callers should choose one operation without defining a whole object. A closure can adapt an existing function or capture small configuration. Keep the signature narrow so it is easy to test; a function value may be nil, so establish whether nil is allowed.","reference":"https://go.dev/ref/spec","title":"A signature is a contract you can pass","watchOut":"A nil function value can be compared to nil, but calling it panics. Other function values cannot be compared for equality."},{"caption":"No implements declaration connects the type to the interface.","id":"interfaces.implicit","mode":"flow","nodes":[{"code":"type Reader interface { Read() }","detail":"Declares a small contract","label":"Consumer"},{"code":"func (s Source) Read()","detail":"Supplies the matching method","label":"Concrete type"},{"code":"var r Reader = Source{}","detail":"Satisfaction is checked implicitly","label":"Assignment"}],"practical":"Define the interface next to the function that consumes it, using only the methods that function needs. Existing types can then satisfy it without knowing about your package. A compile-time assignment to the interface is a useful way to document and check a type intended to satisfy it.","reference":"https://go.dev/ref/spec","title":"The consumer defines the behavior it needs","watchOut":"Method names alone are insufficient. Parameter and result types must match the interface signature exactly."},{"caption":"Convenient method-call syntax does not change interface satisfaction.","id":"interfaces.method-sets","mode":"comparison","nodes":[{"code":"func (t T) Read()","detail":"Belongs to T and *T","label":"Value receiver"},{"code":"func (t *T) Write()","detail":"Belongs to *T","label":"Pointer receiver"},{"code":"var w Writer = &value","detail":"The assigned type must supply Write","label":"Interface check"}],"practical":"When an interface assignment fails, inspect the type of the assigned expression and the receiver of each required method. An addressable local value may call a pointer method through automatic addressing; that same value still lacks the pointer method in its own method set.","reference":"https://go.dev/ref/spec","title":"Value and pointer types have different method sets","watchOut":"Map elements are not addressable. Store pointers in the map or copy, modify and assign a value back."},{"caption":"Both parts must be absent for the interface itself to be nil.","id":"interfaces.nil","mode":"comparison","nodes":[{"code":"var x any","detail":"No dynamic type and no value","label":"Nil interface"},{"code":"var p *Item = nil","detail":"A pointer type with a nil value","label":"Typed nil"},{"code":"x = p","detail":"Dynamic type exists, so x != nil","label":"Boxed pointer"}],"practical":"An interface holding a typed nil pointer still has a dynamic type. This commonly appears when a function returns an error interface from a typed pointer variable. Return a literal nil on the success path, and make nil-receiver behavior explicit for methods intended to support it.","reference":"https://go.dev/ref/spec","title":"An interface carries a type and a value","watchOut":"An interface nil check does not prove that calling a method on the contained value is safe."},{"caption":"A type switch can handle nil, known types and a default case.","id":"interfaces.type-switch","mode":"flow","nodes":[{"code":"value any","detail":"The dynamic type is not yet known","label":"Input"},{"code":"switch v := value.(type)","detail":"Choose a concrete type case","label":"Dispatch"},{"code":"case string:","detail":"v has the selected type","label":"Typed branch"}],"practical":"Use a type switch when an API intentionally accepts several unrelated kinds of values. Put the type-dependent behavior in a small boundary function, then pass concrete values into the rest of your code. A case listing multiple types leaves the case variable with the original interface type.","reference":"https://go.dev/ref/spec","title":"Inspect a dynamic type once at the boundary","watchOut":"A type switch sees the exact dynamic type. A named string type is not the same case as string unless you handle it explicitly."},{"caption":"Embedding is composition with promoted selectors.","id":"interfaces.embedding","mode":"flow","nodes":[{"code":"type Outer struct { Inner }","detail":"Outer contains an Inner value","label":"Embedded field"},{"code":"outer.Run()","detail":"A convenient path to Inner.Run","label":"Promotion"},{"code":"outer.Inner.Run()","detail":"The contained value is still there","label":"Explicit path"}],"practical":"Use embedding to expose a contained type deliberately, not to inherit an identity. The embedded value remains a field with its own receiver and state. A field or method on the outer type can hide a promoted selector; ambiguous promoted names must be reached through the explicit field path.","reference":"https://go.dev/ref/spec","title":"Promotion makes fields and methods easier to reach","watchOut":"Outer is not assignable to Inner just because Inner is embedded in it. Promoted methods can nevertheless satisfy interfaces."},{"caption":"String returns text; it does not print or change the value.","id":"interfaces.stringer","mode":"flow","nodes":[{"code":"type Label int","detail":"Carries application meaning","label":"Your type"},{"code":"String() string","detail":"Returns a readable representation","label":"Method"},{"code":"fmt.Sprint(label)","detail":"Uses the Stringer contract where applicable","label":"Formatting"}],"practical":"Keep String useful for logs and human-facing diagnostics. Some format verbs request a numeric or other specific representation, so not every fmt operation uses String. Separate machine serialization from String when a stable wire format is required.","reference":"https://pkg.go.dev/fmt#Stringer","title":"Formatting can ask the value how to display itself","watchOut":"Formatting the same value with a string verb from inside its own String method can recurse. Convert to the underlying type first."},{"caption":"any is an alias for interface{}; it is not a compile-time generic type parameter.","id":"interfaces.empty","mode":"flow","nodes":[{"code":"var value any = \"go\"","detail":"Any type can be held","label":"Store"},{"code":"text, ok := value.(string)","detail":"Ask for a specific dynamic type","label":"Recover type"},{"code":"if ok { use(text) }","detail":"Operate after checking the assertion","label":"Use safely"}],"practical":"Use any at a deliberately untyped boundary, such as decoding heterogeneous data. Prefer a concrete type when the caller and callee already agree on the shape. A checked type assertion reports failure without panic; an unchecked assertion is appropriate only when the contract guarantees the type.","reference":"https://go.dev/ref/spec","title":"any preserves a dynamic value but promises no methods","watchOut":"Saying any accepts every type does not mean every operation is legal on the resulting interface value."},{"caption":"A constraint describes permitted types; a type argument selects one of them.","id":"generics.type-parameters","mode":"flow","nodes":[{"code":"[]string","detail":"Supplies an element type","label":"Caller"},{"code":"func Keep[T any](in []T)","detail":"T is checked at compile time","label":"Generic function"},{"code":"[]T","detail":"No per-element type assertion","label":"Typed result"}],"practical":"Keep a type parameter connected to the values whose type relationship matters. The compiler often infers it from ordinary arguments, but explicit instantiation is available when inference has no evidence. Generic code may use only the operations guaranteed by its constraint.","reference":"https://go.dev/ref/spec","title":"One algorithm keeps the caller’s element type","watchOut":"An any constraint does not permit arithmetic, ordering or arbitrary methods on T."},{"caption":"A type-set interface can be a constraint without being usable as an ordinary value type.","id":"generics.constraints","mode":"flow","nodes":[{"code":"int","detail":"Allows the predeclared int type","label":"Exact member"},{"code":"~int","detail":"Also allows named types based on int","label":"Underlying member"},{"code":"type Number interface { … }","detail":"Allows ~int or ~float64; every member must support the operation","label":"Union"}],"practical":"Choose the smallest useful type set for the algorithm. Use cmp.Ordered for ordering and comparable when equality or map keys are needed. The tilde permits named types with the given underlying type. Constraints with type terms belong in type-parameter positions, not in ordinary variables.","reference":"https://pkg.go.dev/cmp#Ordered","title":"The type set controls the operations you may use","watchOut":"constraints is not a standard-library package. The experimental golang.org/x/exp/constraints package is a separate dependency."},{"caption":"Each instantiation keeps its element type through every operation.","id":"generics.containers","mode":"flow","nodes":[{"code":"Stack[string]","detail":"Fixes the stored element type","label":"Instantiate"},{"code":"func (s *Stack[T]) Push(v T)","detail":"Reuses T from the receiver","label":"Receiver"},{"code":"var s Stack[int]","detail":"Design operations to accept nil storage","label":"Zero value"}],"practical":"A generic container should preserve the caller’s type and provide a clear empty-state contract. Return a value and a boolean when an element may be absent. Clearing removed pointer-bearing elements can avoid retaining objects through the backing slice after a pop.","reference":"https://go.dev/ref/spec","title":"The receiver carries the container’s type argument","watchOut":"The zero value is useful only if the implementation supports it. Test an empty container before adding constructor requirements."},{"caption":"Go 1.27 adds method-specific type parameters.","id":"generics.methods","mode":"flow","nodes":[{"code":"Bag[E]","detail":"E is fixed by the receiver","label":"Receiver type"},{"code":"Map[F any]","detail":"F belongs to this method","label":"Method parameter"},{"code":"Bag[F]","detail":"The mapping can change the element type","label":"Result type"}],"practical":"Keep the receiver’s parameter and the method’s parameter separate in your reasoning. A mapping function consumes E and produces F; a result container stores F. The caller can often infer F from the callback. This lesson uses the Go 1.27 toolchain bundled with GopherForge.","reference":"https://go.dev/doc/go1.27","title":"A method can transform to a new element type","watchOut":"Interface methods cannot declare type parameters, and a generic method cannot implement an interface method."},{"caption":"A type parameter should express a relationship the ordinary signature cannot express as clearly.","id":"generics.when-not-to","mode":"comparison","nodes":[{"code":"func Print(v Record)","detail":"Best when one type is enough","label":"Concrete type"},{"code":"func Print(v Stringer)","detail":"Best when only behavior matters","label":"Small interface"},{"code":"func Clone[T any]([]T) []T","detail":"Preserves the element type relationship","label":"Type parameter"}],"practical":"Start with the required behavior and the result type. If the caller needs the same concrete element type back, generics can carry that relationship. If the function only invokes one method and returns no type-related result, a small interface often communicates the contract more directly.","reference":"https://go.dev/blog/when-generics","title":"Choose the abstraction that preserves the needed relationship","watchOut":"Interface use does not guarantee a heap allocation, and generics do not guarantee faster code. Measure a real hot path first."},{"caption":"Wrapping links the new error to the old one instead of replacing its identity.","id":"errors.wrapping","mode":"flow","nodes":[{"code":"err := read()","detail":"The original failure","label":"Cause"},{"code":"fmt.Errorf(\"load: %w\", err)","detail":"Adds a message and an unwrap link","label":"Context"},{"code":"errors.Is(err, target)","detail":"Can still recognize the cause","label":"Caller"}],"practical":"Wrap where you can add useful operation context, and avoid repeating the same information at every layer. The percent-v verb formats an error as text; percent-w wraps it for later inspection. Wrapping exposes the cause as part of your API, so decide whether callers should be allowed to depend on it.","reference":"https://pkg.go.dev/errors","title":"Context can preserve the original cause","watchOut":"Only wrap a real non-nil error. A success path should return nil directly."},{"caption":"Inspect the error contract instead of parsing the human-readable message.","id":"errors.is-and-as","mode":"comparison","nodes":[{"code":"errors.Is(err, target)","detail":"Does a matching cause exist?","label":"Identity"},{"code":"errors.As(err, &typed)","detail":"Can a matching error type be extracted?","label":"Type"},{"code":"Unwrap() error","detail":"Inspection follows wrapped causes","label":"Chain"}],"practical":"Use Is for sentinel conditions that callers branch on and As for structured details such as a status or path. Both can traverse wrapped errors. Declare the destination variable for As first and pass its address; pointer error types require a pointer-valued destination variable.","reference":"https://pkg.go.dev/errors","title":"Identity and type answer different questions","watchOut":"Comparing Error() strings is brittle. Messages can change while the error identity and type remain stable."},{"caption":"All ordinary return paths pass through the registered cleanup.","id":"errors.defer","mode":"stack","nodes":[{"code":"resource, err := open()","detail":"Handle a failure first","label":"Acquire"},{"code":"defer resource.Close()","detail":"Cleanup is now tied to this function","label":"Register"},{"code":"return result","detail":"Deferred cleanup runs before the caller continues","label":"Exit"}],"practical":"Register a close only after acquisition succeeds. Defer also runs during panic unwinding in the same goroutine. If closing can report a relevant failure, decide how that error participates in the result rather than discarding it by habit.","reference":"https://go.dev/ref/spec","title":"Cleanup belongs next to successful acquisition","watchOut":"Calling os.Exit does not run deferred functions. A defer in a long loop also waits until the surrounding function exits."},{"caption":"The error interface is one method; behavior and metadata can live together.","id":"errors.custom-type","mode":"flow","nodes":[{"code":"type ParseError struct { Line int }","detail":"Fields describe the failure","label":"Data"},{"code":"Error() string","detail":"Supplies the human-readable message","label":"Contract"},{"code":"errors.As(err, &parseErr)","detail":"Recovers the structured fields","label":"Inspection"}],"practical":"Choose value or pointer receivers consistently with how the error will be returned and inspected. Keep Error free of side effects, because logging may call it more than once. An Unwrap method can expose a lower-level cause when that cause is part of the intended contract.","reference":"https://pkg.go.dev/errors","title":"An error can carry structured information","watchOut":"Avoid returning a typed nil pointer as an error interface; the resulting interface is non-nil."},{"caption":"Panic is an exceptional control flow, not a replacement for an error result.","id":"errors.panic","mode":"comparison","nodes":[{"code":"return err","detail":"The caller decides how to handle it","label":"Expected failure"},{"code":"panic(\"invalid state\")","detail":"Stops normal execution in this goroutine","label":"Broken invariant"},{"code":"defer cleanup()","detail":"Runs while the stack unwinds","label":"Cleanup"}],"practical":"Return errors for invalid input, missing files and canceled operations that callers can reasonably expect. Reserve panic for contracts that cannot continue safely, or for a deliberate internal boundary that will recover. An unrecovered panic terminates the program.","reference":"https://go.dev/ref/spec","title":"Ordinary failures and broken invariants have different exits","watchOut":"A deferred recover in one goroutine cannot catch a panic that happens in another goroutine."},{"caption":"Recovery stops the unwind and lets the enclosing function return; it does not resume the panicking statement.","id":"errors.recover","mode":"flow","nodes":[{"code":"defer func() { ... }()","detail":"Registers a recovery function","label":"Boundary"},{"code":"panic(cause)","detail":"Begins unwinding this goroutine","label":"Unwind"},{"code":"r := recover()","detail":"A direct call in the deferred function catches it","label":"Recover"}],"practical":"Put recovery at a boundary that can decide what a failed operation means, such as handling one request. Convert the recovered failure into an explicit result and record enough context to diagnose the bug. Do not hide unexpected failures in an apparently successful zero result.","reference":"https://go.dev/ref/spec","title":"Recover must run inside deferred cleanup","watchOut":"Calling recover through a non-deferred helper does not recover the panic. The recovering call must be made directly by the deferred function."},{"caption":"The import path locates the package; the package declaration names it in source.","id":"modules.import-path","mode":"flow","nodes":[{"code":"module example.com/tools","detail":"Declared in go.mod","label":"Module"},{"code":"format/","detail":"Package location below the module root","label":"Directory"},{"code":"example.com/tools/format","detail":"Module path joined with that directory","label":"Import"}],"practical":"Keep the distinction between path and local name clear. A package may declare a name different from its directory, and an import alias can choose another local spelling. Import cycles are rejected, so arrange dependencies to flow from higher-level features toward shared lower-level packages.","reference":"https://go.dev/ref/spec","title":"A package path comes from module plus directory","watchOut":"Moving a package directory changes its import path. Renaming only its package clause changes the name used by importing code."},{"caption":"Export is per identifier, including each struct field and method.","id":"modules.exported-by-case","mode":"comparison","nodes":[{"code":"type Config struct { Port int }","detail":"Names beginning with uppercase are visible","label":"Exported"},{"code":"func parse()","detail":"Lowercase names remain package-local","label":"Internal"},{"code":"config.Port","detail":"An exported type may still have private fields","label":"Access"}],"practical":"Give exported names useful documentation and keep implementation helpers private. Visibility applies between packages, not between files in the same package. Standard-library encoders such as encoding/json normally inspect exported struct fields, so field visibility also affects serialization.","reference":"https://go.dev/ref/spec","title":"Capitalization marks the package boundary","watchOut":"An exported struct type does not automatically export its lowercase fields."},{"caption":"Production code and test code are compiled together according to the chosen test package.","id":"modules.tests","mode":"flow","nodes":[{"code":"parser_test.go","detail":"Included by the test build","label":"File"},{"code":"func TestParse(t *testing.T)","detail":"Names the behavior being tested","label":"Entry"},{"code":"t.Run(name, func(t *testing.T))","detail":"Reports each named case separately","label":"Cases"}],"practical":"Write tables around the observable contract: normal input, boundaries and failures. Use Fatal when continuing would make the rest of the test meaningless, and Error when collecting several independent mismatches is useful. Keep test data independent so adding a case does not change another case’s state.","reference":"https://pkg.go.dev/testing","title":"A test is ordinary Go with a testing entry point","watchOut":"Tests in package name_test exercise the exported API; tests in the same package can also inspect unexported details."},{"caption":"Read exported names with their package qualifier before deciding whether they are clear.","id":"modules.naming","mode":"flow","nodes":[{"code":"example.com/project/cache","detail":"Locates the package","label":"Import path"},{"code":"package cache","detail":"Supplies the default qualifier","label":"Package name"},{"code":"cache.Store","detail":"The two words are read together","label":"Public name"}],"practical":"Prefer short, specific package names that describe the responsibility. Avoid repeating the package name in every exported identifier: cache.Store is usually clearer than cache.CacheStore. An import alias resolves a local naming conflict without changing the package’s own public name.","reference":"https://go.dev/ref/spec","title":"The package name becomes part of every selector","watchOut":"A vague package name such as utils tends to gather unrelated responsibilities and makes the dependency direction harder to understand."},{"caption":"Within a package, variable dependency analysis also affects initialization order.","id":"modules.init","mode":"flow","nodes":[{"code":"imported packages","detail":"Initialize before their importers","label":"Dependencies"},{"code":"variables, then init()","detail":"Prepare package state","label":"Package"},{"code":"main.main()","detail":"Runs after initialization completes","label":"Program"}],"practical":"Prefer explicit constructors when configuration or failure handling belongs to the caller. Init functions take no arguments and return no result, which makes them a poor place for recoverable setup. Several init functions are allowed, but hidden dependence on file presentation order makes maintenance harder.","reference":"https://go.dev/ref/spec","title":"Initialization follows dependencies before main","watchOut":"A goroutine started during init may continue running while later initialization proceeds. It needs explicit synchronization if ordering matters."},{"caption":"Completion of the exchange establishes synchronization between the participating goroutines.","id":"concurrency.unbuffered-rendezvous","mode":"flow","nodes":[{"code":"ch <- value","detail":"Waits for a receiver","label":"Sender"},{"code":"make(chan int)","detail":"No queued value slot","label":"Rendezvous"},{"code":"value := <-ch","detail":"Waits for a sender","label":"Receiver"}],"practical":"Use an unbuffered channel when handing over a value should wait until a receiver is ready. Reason about both sides before launching work: a send performed before any receiver can run has nowhere to go. A channel communicates values and coordinates timing at the same time.","reference":"https://go.dev/ref/spec","title":"A send and a receive meet at one point","watchOut":"Sending and then receiving on the same unbuffered channel in one goroutine blocks at the send."},{"caption":"A go statement does not provide an implicit join or keep main alive.","id":"concurrency.no-handle","mode":"flow","nodes":[{"code":"go work()","detail":"Begins a goroutine; returns no handle","label":"Start"},{"code":"done := make(chan struct{})","detail":"Choose a completion signal","label":"Coordinate"},{"code":"<-done","detail":"Observe completion explicitly","label":"Wait"}],"practical":"Pick a completion contract before starting a goroutine. A closed channel can signal one operation’s completion; a WaitGroup can join several operations. Pass cancellation and result paths deliberately so a caller can stop and collect the work it starts.","reference":"https://go.dev/ref/spec","title":"Starting work is separate from waiting for it","watchOut":"When main returns, the program exits even if other goroutines have unfinished work."},{"caption":"Close is a statement about the stream ending, not about discarding its queued values.","id":"concurrency.channel-close","mode":"flow","nodes":[{"code":"ch <- value","detail":"Send every value first","label":"Produce"},{"code":"close(ch)","detail":"Signal the end of production","label":"Finish"},{"code":"for v := range ch","detail":"Read remaining values, then stop","label":"Drain"}],"practical":"Give exactly one owner responsibility for closing. If multiple workers send, a coordinator can wait for all of them and close the results channel afterward. Receivers normally do not close because they cannot know that every sender has finished.","reference":"https://go.dev/ref/spec","title":"The sender announces that no more values are coming","watchOut":"Sending to a closed channel or closing it twice panics. A channel used only for coordination does not always need to be closed."},{"caption":"If several cases can proceed, select chooses one; source order is not a priority rule.","id":"concurrency.select-context","mode":"comparison","nodes":[{"code":"case v := <-values:","detail":"Continue with a received value","label":"Work becomes ready"},{"code":"case <-ctx.Done():","detail":"Return the context error","label":"Cancellation"},{"code":"select { ... }","detail":"The goroutine waits","label":"Neither ready"}],"practical":"Make every potentially blocking send or receive part of the cancellation design. A context is a signal, so the operation must actually observe it. When a channel may close, use the receive boolean to distinguish the end of the stream from a real zero-valued item.","reference":"https://pkg.go.dev/context","title":"Wait for work and cancellation together","watchOut":"Cancellation does not forcibly stop a goroutine. Work that never checks ctx.Done can keep running."},{"caption":"Every access participating in the shared invariant must follow the same locking rule.","id":"concurrency.mutex","mode":"flow","nodes":[{"code":"mu.Lock()","detail":"Wait for exclusive access","label":"Enter"},{"code":"counter++","detail":"Read and modify the protected state","label":"Update"},{"code":"mu.Unlock()","detail":"Allow the next owner to enter","label":"Leave"}],"practical":"Keep the critical section short and make lock ownership easy to see. A deferred unlock protects early returns, while an explicit unlock may be clearer around a small block. Use a channel when transferring ownership expresses the operation better than protecting shared mutable state.","reference":"https://pkg.go.dev/sync#Mutex","title":"One lock protects one shared invariant","watchOut":"Protect reads as well as writes. Copying a used mutex or taking the same mutex twice can break the synchronization contract."},{"caption":"A fixed worker count bounds concurrent processing, not the total number of jobs.","id":"concurrency.worker-pool","mode":"fanout","nodes":[{"code":"jobs <- job","detail":"One producer feeds the queue","label":"Jobs channel"},{"code":"for job := range jobs","detail":"Processes a job at a time","label":"Worker A"},{"code":"for job := range jobs","detail":"Shares the same bounded workload","label":"Worker B"}],"practical":"Coordinate the full lifecycle: start workers, deliver jobs, close the jobs stream, wait for workers, then close the results stream. A separate results consumer may need to run while jobs are produced so backpressure cannot deadlock the producer.","reference":"https://go.dev/ref/spec","title":"Bound the workers while letting jobs flow","watchOut":"Do not close results from an individual worker. Another worker may still be sending."},{"caption":"Buffering changes when a send blocks; it does not remove synchronization requirements.","id":"concurrency.buffered","mode":"sequence","nodes":[{"code":"make(chan int, 2)","detail":"Two sends may queue without receivers","label":"Space available"},{"code":"ch <- next","detail":"The sender waits for space","label":"Buffer full"},{"code":"v := <-ch","detail":"Frees one queued slot","label":"Receive"}],"practical":"Choose capacity to express the intended amount of queued work. A small buffer can smooth bursts and decouple short timing differences. It cannot fix a missing receiver or an endless producer; once capacity is exhausted, backpressure still reaches the sender.","reference":"https://go.dev/ref/spec","title":"A channel buffer has a finite number of slots","watchOut":"len(ch) is a momentary queue size, not a reliable precondition for a future send or receive."},{"caption":"A closed channel may still contain unread values.","id":"concurrency.range-and-close","mode":"flow","nodes":[{"code":"ch <- value","detail":"Values may already be buffered","label":"Queue"},{"code":"close(ch)","detail":"No new sends are allowed","label":"End production"},{"code":"for v := range ch","detail":"Ends after the buffer is empty","label":"Drain and stop"}],"practical":"Use range when the entire stream should be consumed until its producer finishes. If cancellation is also required, use a select loop and inspect the two-result receive. Assign close ownership to the producer or the coordinator that knows all producers are done.","reference":"https://go.dev/ref/spec","title":"The receiver drains before the loop ends","watchOut":"Ranging over a nil channel blocks forever. A never-closed stream also never ends by itself."},{"caption":"Default changes a blocking select into a try operation.","id":"concurrency.select-default","mode":"comparison","nodes":[{"code":"case value := <-ch:","detail":"Receive without waiting","label":"Ready case"},{"code":"default:","detail":"Take the fallback immediately","label":"No ready case"},{"code":"select without default","detail":"Wait until a case can proceed","label":"Blocking alternative"}],"practical":"Use a default case when a skipped operation is part of the contract, such as a best-effort status update. A loop with default can spin continuously when no work is ready. Prefer a blocking select with cancellation or an explicit timing source for a waiting loop.","reference":"https://go.dev/ref/spec","title":"Default means continue immediately when nothing is ready","watchOut":"Default does not run after a timeout and does not wait briefly. It is selected immediately when no communication is ready."},{"caption":"A bidirectional channel can be passed to a directional parameter.","id":"concurrency.direction","mode":"flow","nodes":[{"code":"chan int","detail":"Can send, receive and close","label":"Owner"},{"code":"chan<- int","detail":"May send and close","label":"Producer parameter"},{"code":"<-chan int","detail":"May receive only","label":"Consumer parameter"}],"practical":"Use direction in function signatures to communicate roles and let the compiler reject accidental reverse operations. The owner still needs a runtime lifecycle rule: a send-only parameter can close a channel, but that ability does not establish that it is the correct owner to do so.","reference":"https://go.dev/ref/spec","title":"The type limits who may send or receive","watchOut":"Direction is a permission, not an ownership guarantee. Two senders can still race to close unless the design assigns one closer."},{"caption":"Do does not return to any caller until the one initialization call has finished.","id":"concurrency.once","mode":"fanout","nodes":[{"code":"once.Do(initialize)","detail":"The first caller runs the function","label":"One shared Once"},{"code":"once.Do(initialize)","detail":"Waits if initialization is in progress","label":"Caller A"},{"code":"once.Do(initialize)","detail":"Observes the completed initialization","label":"Caller B"}],"practical":"Keep the Once next to the state it protects, and keep that state in one shared object. It is suitable for initialization that must run at most once. Use another design if an operation may fail and needs retries; Once records the attempt rather than guaranteeing successful initialization.","reference":"https://pkg.go.dev/sync#Once","title":"Concurrent callers share one completed initialization","watchOut":"If the function panics, Once still considers it done. Calling Do recursively on that same Once deadlocks."},{"caption":"The same operation can use files, memory buffers or other implementations.","id":"stdlib.io","mode":"flow","nodes":[{"code":"io.Reader","detail":"Produces bytes","label":"Source"},{"code":"copy or transform","detail":"Works against the small contracts","label":"Transformation"},{"code":"io.Writer","detail":"Accepts bytes","label":"Destination"}],"practical":"Accept interfaces that describe only the I/O behavior the function uses. A reader may return bytes and an error in the same call; process those bytes before the error. Standard helpers such as io.Copy and io.ReadAll handle the protocol details, but ReadAll uses memory proportional to the input.","reference":"https://pkg.go.dev/io","title":"Separate the operation from the transport","watchOut":"Do not assume one Read fills the requested buffer. For an exact byte count, use io.ReadFull."},{"caption":"Decoding into an existing value can preserve fields absent from the input.","id":"stdlib.json","mode":"flow","nodes":[{"code":"type Config struct { Name string }","detail":"Only exported fields are considered","label":"Go value"},{"code":"`json:\"name,omitempty\"`","detail":"Controls naming and omission","label":"Field tag"},{"code":"json.Marshal(config)","detail":"Encoding can return an error","label":"JSON bytes"}],"practical":"Treat tags as part of the external contract and test representative encoded values. Decode into a fresh struct when missing fields should become zero. Use a pointer field when an absent field must be distinguished from a present zero, and consider DisallowUnknownFields for strict input.","reference":"https://pkg.go.dev/encoding/json","title":"Exported fields and tags define the wire representation","watchOut":"Do not silently ignore Marshal or Unmarshal errors. Lowercase fields remain invisible even if they carry a json tag."},{"caption":"A Duration is an int64 measured in nanoseconds.","id":"stdlib.time","mode":"flow","nodes":[{"code":"5","detail":"A plain number has no readable unit","label":"Quantity"},{"code":"time.Second","detail":"A typed duration constant","label":"Unit"},{"code":"5 * time.Second","detail":"An explicit interval","label":"Timeout"}],"practical":"Use Add and Sub for instants and Before, After or Equal for comparisons. Time values may contain location and monotonic information, so == can differ from Equal. A context timeout or timer is often more useful than Sleep when the operation must be cancelable.","reference":"https://pkg.go.dev/time","title":"Make units visible in every duration","watchOut":"time.Sleep(5) requests five nanoseconds; scheduling overhead determines when execution actually resumes."},{"caption":"slices.SortFunc takes a three-way comparison, not a less-than boolean.","id":"stdlib.sort","mode":"flow","nodes":[{"code":"cmp.Compare(a.Year, b.Year)","detail":"Negative, zero or positive","label":"Primary key"},{"code":"if result == 0","detail":"Only now compare another key","label":"Equal primary"},{"code":"cmp.Compare(a.Name, b.Name)","detail":"Produces the final ordering","label":"Secondary key"}],"practical":"Make the comparison consistent and transitive so the sorting algorithm can rely on it. Sorting changes the supplied slice in place; clone first if callers need the original order. Use SortStableFunc when equal elements must retain their original relative order.","reference":"https://pkg.go.dev/slices#SortFunc","title":"Compare the first key, then break ties with the second","watchOut":"Subtracting integers as a comparator can overflow. cmp.Compare expresses the ordering without that overflow risk."},{"caption":"The context carries a cancellation signal; it does not interrupt work automatically.","id":"stdlib.context","mode":"flow","nodes":[{"code":"ctx, cancel := context.WithTimeout(...)","detail":"Sets the lifetime","label":"Caller"},{"code":"select { case <-ctx.Done(): }","detail":"Observes the signal","label":"Wait"},{"code":"return ctx.Err()","detail":"Reports cancellation or deadline","label":"Finish"}],"practical":"Pass context as the first parameter and propagate it to operations that already accept one. Call the returned cancel function to release resources, even if the deadline eventually expires. Keep contexts out of long-lived structs unless an API explicitly requires that lifetime.","reference":"https://pkg.go.dev/context","title":"Cancellation has to reach the blocking operation","watchOut":"Do not use context values for optional arguments or general application state. Values are for request-scoped data crossing API boundaries."},{"caption":"The lesson tests real handler behavior with an in-memory transport.","id":"stdlib.http","mode":"flow","nodes":[{"code":"httptest.NewRequest(...)","detail":"Builds an in-memory request","label":"Request"},{"code":"httptest.NewRecorder()","detail":"Captures status, headers and body","label":"Recorder"},{"code":"handler.ServeHTTP(w, r)","detail":"Writes status, headers and body into the recorder","label":"Handler"}],"practical":"Keep HTTP behavior separate from business logic so handler tests can check methods, paths and invalid input directly. Set headers and status before writing a body; the first Write otherwise commits status 200. In GopherForge’s Wasm sandbox, httptest is the supported way to exercise these routes.","reference":"https://pkg.go.dev/net/http/httptest","title":"A handler can be exercised without opening a socket","watchOut":"Passing an in-memory handler test does not claim that the Wasm program can bind a network socket."},{"caption":"strconv parses representations; a numeric type conversion does not parse a string.","id":"stdlib.strconv","mode":"flow","nodes":[{"code":"\"42\"","detail":"May contain invalid or out-of-range data","label":"Text input"},{"code":"n, err := strconv.Atoi(text)","detail":"Conversion must be checked","label":"Parse"},{"code":"n","detail":"Use only after the error decision","label":"Typed result"}],"practical":"Use ParseInt with an explicit base and bit size when the data format requires a specific integer representation. Atoi targets int, whose width depends on the architecture. Distinguish syntax errors from out-of-range values when the user needs a useful message.","reference":"https://pkg.go.dev/strconv","title":"Text parsing returns a value and a failure path","watchOut":"Whitespace is not automatically trimmed by Atoi. Decide whether your input contract allows it and normalize explicitly."},{"caption":"An image.Image is a pixel interface, not a filename or encoded data blob.","id":"stdlib.image","mode":"flow","nodes":[{"code":"ColorModel, Bounds, At","detail":"Describes pixels and their coordinates","label":"Image contract"},{"code":"image.NewRGBA(bounds)","detail":"Stores mutable pixels","label":"Concrete buffer"},{"code":"png.Encode(writer, img)","detail":"Turns pixels into PNG bytes","label":"Encoding"}],"practical":"Read Bounds rather than assuming every image starts at (0,0). Image implementations may be views over shared pixel storage. Rendering and encoding are separate steps: the app can display a PNG written by a program, while the Go program still uses the standard image and encoding interfaces.","reference":"https://pkg.go.dev/image","title":"Pixels and encoded files are separate representations","watchOut":"A rectangle excludes Max. Iterate while x < bounds.Max.X and y < bounds.Max.Y."}],"hints":[{"hint":"Choose evidence another developer can reproduce.","lessonID":"ai.go-workflow","nuance":"A tool can generate and execute code while still misunderstanding the product invariant. Review behavior as well as syntax."},{"hint":"Distinguish what the model is told from what its tools are allowed to do.","lessonID":"ai.repository-guidance","nuance":"Do not share secret values in instruction files or assume that a context exclusion blocks all tool access."},{"hint":"The page is evidence to inspect, not a new instruction source.","lessonID":"ai.trust-boundaries","nuance":"Do not confuse a generated command with an authorized action. Context files and tool permissions solve different problems."},{"hint":"Find the dependency already selected by the build.","lessonID":"ai.verify-generated-go","nuance":"Compiling proves API compatibility for that build; database timing, failover and atomicity require additional evidence."},{"hint":"Home maps a rich internal object to the client view without copying InternalNote. In a real BFF, downstream calls can fail independently; define timeout budgets and whether partial data is acceptable before parallelizing aggregation.","lessonID":"architecture.bff","nuance":"One extra boundary helps clients with genuinely different data and release needs."},{"hint":"Product performs policy without importing storage.","lessonID":"architecture.clean-onion","nuance":"Model missing products and invalid discounts before using this mechanism in production."},{"hint":"Deposit is the command boundary; Summary is the query shape. Both read the same in-memory state here, so there is no projection lag. Separating methods does not by itself require queues, extra services or event replay.","lessonID":"architecture.cqrs","nuance":"If a projection becomes asynchronous, explain stale reads and rebuild procedures to clients and operators."},{"hint":"The Basket operation checks the invariant before mutation, so a rejected addition leaves three items.","lessonID":"architecture.ddd","nuance":"Use richer models where business language and rules justify them."},{"hint":"Two deliveries of event-1 create one effect.","lessonID":"architecture.event-driven","nuance":"Buffering can isolate timing, but it does not guarantee business completion."},{"hint":"Replaying both events yields 30; replaying the prefix yields 50.","lessonID":"architecture.event-sourcing","nuance":"Choose this when temporal history and reconstruction are core requirements."},{"hint":"Register enforces a rule before Store changes.","lessonID":"architecture.layered","nuance":"A feature may touch every horizontal layer, so keep mapping work proportional to the value it protects."},{"hint":"The core dispatches through a function contract, and the startup map explicitly selects available behavior.","lessonID":"architecture.microkernel","nuance":"Extensions in the same process can panic, block or access shared resources; an interface is not a security sandbox."},{"hint":"The dependency contract distinguishes a business answer from a failed lookup.","lessonID":"architecture.microservices","nuance":"Independent ownership helps teams with different release and scaling needs."},{"hint":"Shipping receives the one query it needs instead of the billing map. Both calls stay in the same process. In a real module layout these declarations belong in separate packages, with internal implementation hidden behind each module API.","lessonID":"architecture.modular-monolith","nuance":"One database can support atomic changes, but bypassing module APIs destroys ownership."},{"hint":"Describe the caller's required behavior before naming the implementation.","lessonID":"architecture.package-boundaries","nuance":"A directory tree is not architecture unless dependencies and responsibilities actually follow its boundaries."},{"hint":"The pipeline first trims and then capitalizes, so order matters.","lessonID":"architecture.pipes-filters","nuance":"Use stages when transformations compose naturally and need separate tests."},{"hint":"Trace a single request rather than adding layers to an abstract diagram.","lessonID":"architecture.ports-and-adapters","nuance":"Mocking a dependency tests a contract in isolation; it does not verify the concrete adapter honors that contract."},{"hint":"Handle is pure application behavior, independent of a provider SDK. An outer adapter decodes the event and serializes the result. Moving a side effect into this function would require an idempotency policy, not a process-global seen map.","lessonID":"architecture.serverless","nuance":"Functions suit bounded event-driven tasks and variable workloads."},{"hint":"The entry point decides how to report failure; total only parses and computes. The result is 36. There is no remote call, queue or dependency container because this variation has not appeared in the problem.","lessonID":"architecture.simple-monolith","nuance":"Start splitting when different responsibilities change independently or teams need ownership boundaries."},{"hint":"The request and response encode units in field names.","lessonID":"architecture.soa","nuance":"Broad shared services can reduce integration duplication but become release bottlenecks."},{"hint":"Compare the cost of a boundary with the change it makes easier.","lessonID":"architecture.styles-and-clean-code","nuance":"Distribution adds failure modes and operational work; it is not a prerequisite for clean Go code."},{"hint":"RenameProject owns normalization and validation for one operation.","lessonID":"architecture.vertical-slice","nuance":"Extract a shared domain rule when several slices genuinely enforce the same invariant."},{"hint":"The example exposes acceptance and later consumption as different operations.","lessonID":"architecture.web-queue-worker","nuance":"Use a durable queue and idempotent worker for valuable work."},{"hint":"main owns the client and schedules its cleanup exactly once.","lessonID":"clean-production.composition","nuance":"No. The composition root owns the shared client; requests borrow it and close only request-scoped resources such as rows or bodies."},{"hint":"Err identifies cancellation broadly; Cause retains the chosen explanation.","lessonID":"clean-production.context-contracts","nuance":"No. It removes cancellation and deadline propagation; detached work needs a separately owned context, budget and completion or recovery policy."},{"hint":"The reader contract is declared near its consumer and contains one capability.","lessonID":"clean-production.package-apis","nuance":"Prefer the narrow capability the consumer needs; keep driver and transaction details in adapters and verify those with real integration tests."},{"hint":"The duration is explicitly milliseconds, the amount is cents, and the large token amount is parsed without a floating-point round trip.","lessonID":"clean-production.time-money","nuance":"No. Parse exact integer base units or validated decimal text directly, and make scaling, range and rounding explicit."},{"hint":"NewPool rejects zero workers and a queue smaller than the worker count. The successful caller receives a valid configuration. No goroutines are started in this example, which keeps validation separate from lifecycle and cleanup.","lessonID":"clean.configuration","nuance":"Use functional options only when they improve an evolving API."},{"hint":"Wrapping preserves ErrMissing for errors.Is while adding the project operation for a human. The program prints once at the boundary. Replacing %w with %v would keep the message but lose this cause chain.","lessonID":"clean.errors","nuance":"Expose stable error categories only when they are part of the package contract."},{"hint":"FirstByte accepts only the Read behavior that io.ReadFull needs, so a string reader works without an inheritance relationship. The error still belongs to the result: an empty reader would return EOF, not a valid zero byte.","lessonID":"clean.interfaces","nuance":"Do not define a giant interface beside an implementation merely to mock it."},{"hint":"Delay has a duration type rather than an undocumented integer unit.","lessonID":"clean.names","nuance":"Choose brevity in small scopes and precision at boundaries."},{"hint":"The constructor copies input and Bytes copies output, so neither caller mutation changes the retained message.","lessonID":"clean.ownership","nuance":"Copies cost memory and time, so measure large buffers before copying everywhere."},{"hint":"The boundary values 1000 and 1001 make the tariff transition visible.","lessonID":"clean.refactoring","nuance":"Run go test and go vet for correctness, race tests for exercised concurrency, and benchmarks for a suspected performance issue."},{"hint":"UpperReader decorates Read while preserving its byte count and error.","lessonID":"clean.solid","nuance":"Go has no class inheritance hierarchy to organize by default."},{"hint":"The cases distinguish trimmed content from two forms of empty input and verify both the value and error presence. In a _test.go file, place the loop in TestNormalize and report the case with t.Errorf or t.Run rather than panic.","lessonID":"clean.table-tests","nuance":"Add integration tests where real serialization, SQL or network contracts matter."},{"hint":"Return a slice that does not share the caller's array after you write.","lessonID":"collections.append-aliasing","nuance":"append writes in place until cap is exceeded. Past cap it allocates and the alias silently ends."},{"hint":"Return [3]int, not a slice. Copy the first three elements.","lessonID":"collections.arrays","nuance":"[4]int and [3]int are different types. Assigning an array copies every element."},{"hint":"s[i] checks len. s[:n] checks cap.","lessonID":"collections.bounds","nuance":"Indexing into unused capacity panics. Reslicing into it is how a slice grows back."},{"hint":"Separate the slice header from its elements and identify every writer.","lessonID":"collections.concurrent-slices","nuance":"Independent slots are safe only with fixed ownership and synchronization before the final read."},{"hint":"Call fn on each element and collect the results. fn is a value, not a method.","lessonID":"collections.function-values","nuance":"The Tour: functions are values. The type is func(int) int, including the argument and the result."},{"hint":"yield returning false must stop the iterator.","lessonID":"collections.iterators","nuance":"A range-over-func is a push loop. Breaking the for is yield returning false, not a channel close."},{"hint":"len is what you may index. cap is what you may reslice into.","lessonID":"collections.length-capacity","nuance":"make([]int, 0, 10) has room and is not indexable. make([]int, 10) is."},{"hint":"make the map. new the int. Do not swap them.","lessonID":"collections.make-and-new","nuance":"new(map[string]int) is a pointer to nil. Writing through it panics. make returns a usable map."},{"hint":"Use _, ok := m[key]. A stored zero is present.","lessonID":"collections.map-ok","nuance":"elem := m[key] cannot tell missing from zero. delete of a missing key is a no-op."},{"hint":"Collect keys and sort them. Do not range and hope.","lessonID":"collections.map-order","nuance":"Map iteration order is randomised. Tests that assume an order flake."},{"hint":"A missing key is the zero value. Incrementing it is how a counter starts.","lessonID":"collections.map-zero-value","nuance":"Writing to a nil map panics. make, or a literal, before the first write."},{"hint":"var s []int is nil and append still works. []int{} is empty and not nil.","lessonID":"collections.nil-slice","nuance":"JSON encodes nil as null and empty as []. Prefer len(s) == 0 unless the wire cares."},{"hint":"Look for a small cached value that still points into a large input.","lessonID":"collections.retained-buffers","nuance":"Reducing a slice capacity does not copy storage or shorten the backing array lifetime."},{"hint":"range over a string yields runes. i is a byte offset, not a character index.","lessonID":"collections.runes-not-bytes","nuance":"len counts bytes; é uses two in UTF-8. []rune represents Unicode code points, not user-perceived grapheme clusters."},{"hint":"Draw the array once and point both slice windows at it.","lessonID":"collections.slice-walkthrough","nuance":"Capacity clipping controls append reuse; it does not isolate writes to elements already in the slice."},{"hint":"Write into strings.Builder. Do not concatenate in a loop.","lessonID":"collections.strings-builder","nuance":"Repeated runtime concatenation can copy growing prefixes. Builder reduces copying; measure allocations and never copy a nonzero Builder."},{"hint":"The map is copied before the pointer is stored.","lessonID":"concurrency.atomic-snapshots","nuance":"No. Atomic publication protects the pointer protocol, not later mutations of reachable state; publish independent immutable data or use a lock."},{"hint":"Find the slowest resource and the queue in front of it.","lessonID":"concurrency.bounded-work","nuance":"An unbounded population of goroutines waiting for a semaphore is still an unbounded queue."},{"hint":"make(chan int, n), send 0..n-1, close, range. No extra goroutine.","lessonID":"concurrency.buffered","nuance":"A buffer of n holds n. The n+1st send from the only goroutine deadlocks."},{"hint":"Identify the stop signal and the acknowledgement as two separate events.","lessonID":"concurrency.cancel-and-join","nuance":"A context only helps at code paths and APIs that observe it; cancellation alone does not join workers."},{"hint":"The sender closes, once. Range until that close.","lessonID":"concurrency.channel-close","nuance":"close is not required for GC. It is a signal. Send after close panics."},{"hint":"Take chan<- int, send, close. A receive in that function should not compile.","lessonID":"concurrency.direction","nuance":"Bidirectional converts to directional. The other way does not. Close is a send-side operation."},{"hint":"The derived context belongs to the group operation.","lessonID":"concurrency.errgroup","nuance":"SetLimit bounds active group functions, not every queued byte. All started work must be joined before its dependencies are released."},{"hint":"Both methods use pointer receivers so calls share the lock owner.","lessonID":"concurrency.lock-ownership","nuance":"The lock is copied while the map storage remains shared. Use a stable lock owner and pointer receivers; test both races and the compound invariant."},{"hint":"Lock, defer Unlock, then read or write the map. Initialise the map in New.","lessonID":"concurrency.mutex","nuance":"A mutex is for state that stays. A channel is for handing a value over. Do not pick by fashion."},{"hint":"go f() returns nothing. If you need the result, give f a channel or a WaitGroup.","lessonID":"concurrency.no-handle","nuance":"There is no join, no Future. A goroutine you forget is a leak, not a warning."},{"hint":"once.Do(fn). Call it twice in the test; fn must run once.","lessonID":"concurrency.once","nuance":"Do is safe for many goroutines. A nil Once panics. Do not copy an Once after first use."},{"hint":"for v := range ch. The loop ends when the sender closes.","lessonID":"concurrency.range-and-close","nuance":"v, ok := <-ch is the same test. ok is false when the channel is closed and empty."},{"hint":"select on the value and on ctx.Done(). Return ctx.Err() when the context wins.","lessonID":"concurrency.select-context","nuance":"A function that takes a context and ignores it cannot be cancelled. The first parameter is the convention."},{"hint":"select { case v := <-ch: ... default: return 0, false }.","lessonID":"concurrency.select-default","nuance":"default means try once. A loop of default-selects is a spin, not a wait."},{"hint":"Separate in-process evidence from an external system boundary.","lessonID":"concurrency.synctest","nuance":"Use the bubble for a deterministic in-process protocol and retain isolated integration tests for external services."},{"hint":"A send on make(chan T) waits for a receive. One goroutine cannot do both.","lessonID":"concurrency.unbuffered-rendezvous","nuance":"The classic deadlock is one line: ch := make(chan int); ch <- 1 in main."},{"hint":"Joining waits for exit; it cannot manufacture an exit path.","lessonID":"concurrency.waitgroup-go","nuance":"Use an error-aware group for returned task errors and keep a separate bounded cancellation path for work that may block."},{"hint":"Close the input after sending. Range in each worker. Wait, then close the output.","lessonID":"concurrency.worker-pool","nuance":"Close the output before Wait and a worker panics mid-send. Reverse the order and you deadlock."},{"hint":"iota counts from zero in the const block. The untyped constant has no size until used.","lessonID":"core.constants","nuance":"1 << 62 as a const is fine; assigned to int32 it overflows. The type arrives at the use."},{"hint":"Convert len(readings) to Celsius before dividing.","lessonID":"core.conversions","nuance":"int and Celsius are different types even when the bits match. The conversion is the point."},{"hint":"Track each name together with the block that declares it.","lessonID":"core.declarations-walkthrough","nuance":"A nested declaration and an assignment have different effects even when the name is spelled identically."},{"hint":"Deferred calls run last-in first-out. Arguments are evaluated when defer is registered.","lessonID":"core.defer-stack","nuance":"defer fmt.Println(i) in a loop captures each i. A closure over a shared i does not."},{"hint":"Walk through one invalid input and one valid input before reading the success return.","lessonID":"core.error-path-walkthrough","nuance":"An error does not universally invalidate every returned value; the called API defines that contract."},{"hint":"Return the value and an error. Do not throw, do not wrap a bool success flag.","lessonID":"core.multiple-returns","nuance":"The error is a value. Ignoring it with _ is how a failure becomes a plausible zero."},{"hint":"Name quot and rem in the signature and use a naked return.","lessonID":"core.named-results","nuance":"The Tour says keep naked returns for short functions. In a long one they hide what leaves."},{"hint":"Type the line exactly. := cannot appear at package level.","lessonID":"core.short-declaration","nuance":"At least one name on the left must be new, or the compiler says no new variables."},{"hint":"Write a switch with no expression. Do not put break at the end of a case.","lessonID":"core.switch","nuance":"Go cases do not fall through. fallthrough is the rare keyword, not the default."},{"hint":"Use every local and every import, or delete them.","lessonID":"core.unused-is-an-error","nuance":"There is no unused-variable warning. The compiler refuses the file."},{"hint":"Read each var before any assign. Name the zero of int, bool, string and a pointer.","lessonID":"core.zero-values","nuance":"There is no uninitialised memory. nil is only for pointers, slices, maps, channels and interfaces."},{"hint":"No driver error does not imply that the predicate matched.","lessonID":"datastores.mongo-atomic","nuance":"No driver error does not mean the predicate matched. Check MatchedCount and handle an absent or stale-version document; one-document atomicity does not cover every business invariant."},{"hint":"Construction and a bounded server operation are separate events.","lessonID":"datastores.mongo-client","nuance":"Connect configures a client; a bounded Ping separately tests current server readiness. Neither promises that future network operations cannot fail or time out."},{"hint":"The consumer may still retain every batch.","lessonID":"datastores.mongo-cursors","nuance":"Streaming only stays memory-bounded when the query and downstream consumer both have explicit limits."},{"hint":"Compare work examined with useful rows returned.","lessonID":"datastores.mongo-indexes","nuance":"The useful plan depends on filter, sort, selectivity and index shape. Explain measures examined work; a client pool setting does not guarantee index use."},{"hint":"Find the stage that consumes the operation deadline.","lessonID":"datastores.mongo-load","nuance":"Client pool capacity, waiting goroutines and total deployment connections are different quantities."},{"hint":"The database cannot undo an effect in another system.","lessonID":"datastores.mongo-transactions","nuance":"The driver can rerun the transaction callback. MongoDB cannot roll back an external payment or email, so make database work repeatable and deliver external effects through an idempotent boundary."},{"hint":"Consider the empty-cache path, including all replicas.","lessonID":"datastores.redis-cache","nuance":"In-process coalescing does not coordinate other replicas or make invalidation races disappear."},{"hint":"Choose behavior for each error class.","lessonID":"datastores.redis-client","nuance":"redis.Nil from GET means this key is absent. A transport failure is a different result; unlimited fallback work during an outage can overwhelm the origin."},{"hint":"A key’s lifetime and a process’s execution lifetime differ.","lessonID":"datastores.redis-coordination","nuance":"Expiry changes the Redis key, not the execution state of an old process. A paused former owner can resume after a new owner starts; the protected resource may need fencing."},{"hint":"Locate waiting before and after server command execution.","lessonID":"datastores.redis-load","nuance":"SLOWLOG measures server execution. Callers can still wait for a client connection or network response; retries can then amplify load or repeat an ambiguous write."},{"hint":"Transport batching and a transactional boundary are different.","lessonID":"datastores.redis-pipeline","nuance":"MULTI/EXEC does not roll back already executed commands after a runtime command error."},{"hint":"The worker can fail between the effect and acknowledgment.","lessonID":"datastores.redis-streams","nuance":"The effect may commit before a worker crashes without acknowledging. Redelivery can then repeat it; pending-entry recovery needs destination-side idempotency."},{"hint":"Give ParseError an Error() string method. Return a pointer so As can find it.","lessonID":"errors.custom-type","nuance":"errors.As needs the type you stored. A value and a pointer are different types here too."},{"hint":"defer Close right after a successful Open. It runs on every return, including panic.","lessonID":"errors.defer","nuance":"defer is function-scoped, not block-scoped. A defer inside a loop waits until the function ends."},{"hint":"Type errors.Is(err, sentinel). Do not compare with ==.","lessonID":"errors.is-and-as","nuance":"== fails the moment anyone wraps. Error() strings break when the wording changes."},{"hint":"Named return err is assigned inside recover. A bare return nil after work() would overwrite it.","lessonID":"errors.panic","nuance":"recover only works in a deferred function. Calling it in the panicked function itself is too late."},{"hint":"defer a function that recover()s and writes the named err. Then call work().","lessonID":"errors.recover","nuance":"Use this at a boundary — one request, one goroutine. It is not a catch block for the whole program."},{"hint":"fmt.Errorf(\"...: %w\", err). %v formats and loses the cause.","lessonID":"errors.wrapping","nuance":"errors.Is and errors.As walk %w. They cannot walk a string you built with +."},{"hint":"Put ~ on each type in the union so a named Celsius still fits.","lessonID":"generics.constraints","nuance":"Without the tilde, only the listed types themselves match. type Celsius float64 would not."},{"hint":"A nil items slice appends fine. Pop returns the zero of T, not nil.","lessonID":"generics.containers","nuance":"var zero T is the zero of whatever T became. T{} is not valid for every type."},{"hint":"Map cannot be a method that introduces U. Write it as a function, or keep U off the receiver.","lessonID":"generics.methods","nuance":"Methods repeat the type's parameters. They cannot add new ones. That is why Map is a function in the libraries."},{"hint":"Keep[T any] and filter with the function you are given.","lessonID":"generics.type-parameters","nuance":"T stays the caller's type. any as a parameter would force an assertion on the way out."},{"hint":"If the constraint is one method and you never need the concrete type, take the interface.","lessonID":"generics.when-not-to","nuance":"A type parameter that is only used as an interface is slower to read and the same at runtime."},{"hint":"Watch which Describe Greet calls. Promotion is not virtual dispatch.","lessonID":"interfaces.embedding","nuance":"The outer method shadows for callers. A promoted sibling still calls the inner one."},{"hint":"return fmt.Sprintf(\"%T\", value). nil is <nil>.","lessonID":"interfaces.empty","nuance":"any is interface{}. Holding a value throws the static type away; %T is how you peek."},{"hint":"Declare the interface next to the function that needs it. One method is enough.","lessonID":"interfaces.implicit","nuance":"Nothing says implements. A type in another package satisfies you without importing you."},{"hint":"A pointer receiver is only on *T. A T value will not satisfy the interface.","lessonID":"interfaces.method-sets","nuance":"Mixing value and pointer receivers on one type is how method-set bugs hide until assignment."},{"hint":"Return a bare nil, not a typed nil pointer stored in an interface.","lessonID":"interfaces.nil","nuance":"An interface is nil only when both type and value are. var p *E; var err error = p is not nil."},{"hint":"fmt.Sprintf the four bytes as a dotted quad. Do not Sprint the value itself.","lessonID":"interfaces.stringer","nuance":"Sprint looks for Stringer. Calling it from String() recurses until the stack blows."},{"hint":"Use value.(type). The one-value assertion panics; the two-value form does not.","lessonID":"interfaces.type-switch","nuance":"The comma-ok assertion is the same shape as a map read, on purpose."},{"hint":"Ask which delays and failures the benchmark does not include.","lessonID":"modules.benchmark-load","nuance":"A microbenchmark measures its own loop and inputs. It may omit network, pool wait, queue growth and overload failures that dominate a real service."},{"hint":"The build process and the deployed service have separate budgets.","lessonID":"modules.build-capacity","nuance":"The -p build flag limits concurrent package work in the toolchain. It does not impose a request, goroutine or database-connection limit on the compiled application."},{"hint":"Integrity, authorization and dependency selection are different layers.","lessonID":"modules.checksums-private","nuance":"A checksum verifies the expected content of a version. It does not select that version, certify its behavior or establish that no vulnerability is known."},{"hint":"A capital letter is the access modifier. There is no export keyword.","lessonID":"modules.exported-by-case","nuance":"Parse is visible. parse is not. The rule is the first letter, including on fields and constants."},{"hint":"State the input budget and the property actually asserted.","lessonID":"modules.fuzz-vulnerability","nuance":"A weak property can pass even when the parser is wrong; choose an oracle tied to the contract."},{"hint":"Follow go.mod, then the subdirectory of the import.","lessonID":"modules.identity-versions","nuance":"A module versions a set of packages together. A package groups source in one directory; the repository name does not override its declared package identifier."},{"hint":"The module path plus the directory is the import path. The last element is the package name.","lessonID":"modules.import-path","nuance":"internal/ is enforced by the compiler. Only code rooted at its parent may import it."},{"hint":"init runs before main, once per package. Do not use it for anything a caller should control.","lessonID":"modules.init","nuance":"init cannot be called. It cannot return an error. A failed init takes down the process."},{"hint":"The package name is the last element of the import path, not the folder's marketing name.","lessonID":"modules.naming","nuance":"import \"text/tabwriter\" gives you tabwriter, not text. A stutter (tabwriter.Writer) is the style."},{"hint":"Count clients, test binaries and parallel subtests together.","lessonID":"modules.parallel-tests","nuance":"Package test binaries and parallel subtests share downstream capacity. Isolate fixtures and bound their combined demand; the race detector does not size a database pool."},{"hint":"Follow where requests spend time, including queues.","lessonID":"modules.profiles-contention","nuance":"A blocked request can spend most of its time waiting while consuming little CPU. Inspect queue, pool and synchronization delays as well as execution samples."},{"hint":"Match resource lifetime to the component that uses it.","lessonID":"modules.startup-ownership","nuance":"The application component owns a shared client across requests, stops new work and drains existing work before closing it. Per-request pools multiply connection and startup costs."},{"hint":"t.Run each case. Name the cases so -run can select one.","lessonID":"modules.tests","nuance":"A table without t.Run hides every failure after the first. Parallel is t.Parallel, not automatic."},{"hint":"Reproducibility and ongoing maintenance both matter.","lessonID":"modules.tools-toolchain","nuance":"A reviewed tool pin makes CI’s command input reproducible. It still needs maintenance; it neither fixes all dependencies to one version nor removes future security work."},{"hint":"Distinguish an explicit generation step from compilation.","lessonID":"modules.vendor-embed","nuance":"Compilation does not automatically invoke go generate. Generation is an explicit workflow step whose tool version and output need their own checks."},{"hint":"Separate a requirement edge from the selected build list.","lessonID":"modules.version-graph","nuance":"The selected version for one module path must satisfy the graph’s minimum requirements. go.sum records content hashes, not a request for the newest version."},{"hint":"Compare the local composition with a separate consumer.","lessonID":"modules.workspace-replace","nuance":"GOWORK=off removes the local workspace composition. That exposes missing published requirements and APIs that only worked through sibling modules or local replacements."},{"hint":"Screen requests two distinct product roles from the same factory, keeping the family consistent.","lessonID":"patterns.abstract-factory","nuance":"This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values."},{"hint":"Only Counter reads or writes total.","lessonID":"patterns.actor-owner","nuance":"Serialize only what needs one owner; a busy owner can become a bottleneck."},{"hint":"SensorAdapter translates Celsius into Fahrenheit and satisfies the consumer’s method implicitly.","lessonID":"patterns.adapter","nuance":"Use an adapter for an actual mismatch. If you own both sides and can make their contracts agree directly, another wrapper may add no value. Adapter changes the interface; Decorator usually preserves it while adding behavior."},{"hint":"Report data and rendering policy vary separately through composition. A different report abstraction can reuse the same renderer. The function contract stays small because only one operation varies in this example.","lessonID":"patterns.bridge","nuance":"If only one dimension varies, Strategy or a direct function argument may describe the design more clearly."},{"hint":"Build validates the path and copies tags into the finished Request. Adding another builder tag does not mutate the already built request. This is a staged mutable builder, not a promise of thread safety.","lessonID":"patterns.builder","nuance":"A builder with one setter per field can obscure a clear struct literal. Use it for genuinely staged or repeated assembly and return validation errors. State whether a builder can be reused and whether products share backing storage."},{"hint":"The producer can leave a blocked send through ctx.Done and closes its own output on return.","lessonID":"patterns.cancellation","nuance":"Cancel on all completion paths to release timers and derived contexts."},{"hint":"Validate delegates in order and returns immediately on an error. The second check is never asked about an empty string after the first failure. An HTTP middleware chain can use a similar continuation shape with a next handler.","lessonID":"patterns.chain","nuance":"Ordering is part of behavior: authentication should usually precede work that leaks private data."},{"hint":"After two failures, a third call is rejected without invoking fail.","lessonID":"patterns.circuit-breaker","nuance":"A concurrent implementation must lock state and admit only a bounded number of half-open probes."},{"hint":"Rename captures the receiver, requested name and old name. Do is guarded against repetition; Undo restores the prior value. This assumes no independent mutation between execution and undo and one owner of the receiver.","lessonID":"patterns.command","nuance":"For durable queues, serialize a command schema and validate it on receipt; a closure cannot survive process exit."},{"hint":"File and Folder satisfy the same Size operation, so the root recursively sums to nine. The interface hides whether a child is a leaf or group. This example assumes an acyclic owned tree and small nonnegative sizes.","lessonID":"patterns.composite","nuance":"Uniform operations can be elegant, but a group-only mutation API need not be forced onto leaves."},{"hint":"Both wrappers retain Operation and delegate exactly once.","lessonID":"patterns.decorator","nuance":"Preserve cancellation, errors and optional interfaces that callers actually depend on."},{"hint":"Buy hides two local state changes behind one operation and validates before mutating.","lessonID":"patterns.facade","nuance":"A facade can become a god object if it owns every policy."},{"hint":"Report.Write owns the stable algorithm and calls the supplied creation hook.","lessonID":"patterns.factory-method","nuance":"Use a plain constructor when the caller can create the dependency directly."},{"hint":"Each forwarding goroutine signals completion, and only the coordinator closes out. main consumes the full merge, so every producer can finish. The sum is deterministic; the individual values can arrive in several valid orders.","lessonID":"patterns.fan-in","nuance":"When a consumer may stop early, use context-aware sends and ensure upstream producers also stop."},{"hint":"Two placements share the same Glyph pointer but retain different positions.","lessonID":"patterns.flyweight","nuance":"An unbounded intern table can retain data forever and consume more memory than it saves."},{"hint":"And evaluates two named conditions from an explicit environment and short-circuits on false.","lessonID":"patterns.interpreter","nuance":"Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics."},{"hint":"CountTo hides how values are generated and stops immediately after the caller breaks at two. iter.Seq is available from Go 1.23. The iterator uses no goroutine or channel because synchronous production is enough.","lessonID":"patterns.iterator","nuance":"For fallible streams, define how errors are delivered, such as iter.Seq2[Value, error] or an Err method."},{"hint":"Submit owns the collaboration rule: notification only follows valid input. The two collaborators do not reference each other. This uses function dependencies because the roles are small and their lifetime is controlled by main.","lessonID":"patterns.mediator","nuance":"As participants grow, split mediators by use case instead of accumulating unrelated branches."},{"hint":"The snapshot copies lines on save and restore, preventing later edits from changing the saved history.","lessonID":"patterns.memento","nuance":"Large histories need memory limits, deltas or durable versioning."},{"hint":"The subscription returns its own cleanup operation. After stop, a later notification has no effect on total. The example assumes a single owner, no reentrant map mutation and listeners whose order does not matter.","lessonID":"patterns.observer","nuance":"Decide whether delivery is synchronous, ordered, droppable or buffered before introducing goroutines."},{"hint":"The clone owns a different slice backing array and a different map, so mutation does not change original. The elements here are immutable strings and integers; pointer or nested slice elements would require another deliberate copy decision.","lessonID":"patterns.prototype","nuance":"Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method."},{"hint":"The proxy invokes its subject once for the repeated key and returns the cached value on the second call. The closure is deliberately single-owner and unbounded for this tiny example; it is not a concurrent production cache.","lessonID":"patterns.proxy","nuance":"Choose a TTL or invalidation policy for changing data and include authorization scope in cache keys where needed."},{"hint":"The operation succeeds on attempt three; permanent errors would stop immediately.","lessonID":"patterns.retry","nuance":"Keep attempt limits small and cap exponential delay before shifts can overflow."},{"hint":"The closure creates one Config for its owner and returns the same pointer twice.","lessonID":"patterns.singleton","nuance":"OnceValue caches a panic as well as a result; it is not a retry mechanism for transient startup failures."},{"hint":"Approve rejects a transition from Draft, then succeeds after Submit.","lessonID":"patterns.state","nuance":"Persisted state machines need concurrency control, transition audit and idempotency."},{"hint":"Present controls copying and delegates ordering to the selected function.","lessonID":"patterns.strategy","nuance":"Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently."},{"hint":"Run fixes loading before formatting and owns the result prefix. Callers replace steps without changing this order. This is a composition-based Go adaptation of Template Method, rather than a claim that Go supports virtual method overrides.","lessonID":"patterns.template-method","nuance":"If every step varies independently, a plain pipeline may be clearer than a framework with many hooks."},{"hint":"Each node dispatches to its matching visitor method. Evaluate traverses child nodes to compute five without putting evaluation policy inside Add. A second visitor could count nodes while using the same node structure.","lessonID":"patterns.visitor","nuance":"Adding a new visitor operation is straightforward, but adding a new node kind changes the Visitor interface and every implementation. This is the main tradeoff. Prefer a switch when the structure and operations are both small and local."},{"hint":"Two workers share one input channel; a coordinator closes results only after both have exited.","lessonID":"patterns.worker-pool","nuance":"This finite example drains every job."},{"hint":"Compare allocation rate, live heap and process memory before choosing a knob.","lessonID":"runtime.gc-budget","nuance":"The runtime memory limit is soft and cannot substitute for a bounded workload or a measured container budget."},{"hint":"Follow every remaining reference path, including caches and blocked workers.","lessonID":"runtime.gc-reachability","nuance":"Eligible for collection does not mean the same bytes disappear from process RSS immediately."},{"hint":"Count tasks, execution slots and operating-system threads as different quantities.","lessonID":"runtime.goroutines-and-threads","nuance":"A low CPU percentage can coexist with severe overload caused by blocked downstream calls and growing queues."},{"hint":"A later owner may reuse storage immediately; the returned value needs a separate lifetime.","lessonID":"runtime.pool-ownership","nuance":"Pool reuse is optional and identity is not guaranteed. An owned copy remains correct with or without reuse. A pool does not replace admission control, a bounded queue or database connection management."},{"hint":"Pick the profile that can actually observe the suspected resource.","lessonID":"runtime.profiles-and-leaks","nuance":"Profiles need workload context; a large cumulative allocation total does not itself establish a live-memory leak."},{"hint":"Separate the language lifetime guarantee from a particular allocation decision.","lessonID":"runtime.stack-and-heap","nuance":"Pointer syntax does not prove a heap allocation, and a value expression is not a promise of zero allocations."},{"hint":"Follow one expired hot key through every replica and retry layer.","lessonID":"services.cache-stampede","nuance":"An in-flight duplicate suppressor is neither a persistent cache nor a distributed lock."},{"hint":"Read the path prefix, route pattern, parameter and response in that order.","lessonID":"services.gin-routing","nuance":"Gin is optional tooling around HTTP; it does not make an application architecture or network policy for you."},{"hint":"Find the point where input first becomes allowed to cause a side effect.","lessonID":"services.gin-validation","nuance":"Required fields and authorization are different checks; valid JSON can still represent an invalid operation."},{"hint":"Follow the request from validation to the final response, including cancellation.","lessonID":"services.http-lifecycle","nuance":"Connection-phase timeouts and a business operation deadline protect different parts of a request."},{"hint":"Identify the client pool, the queue and the server as separate limits.","lessonID":"services.redis-capacity","nuance":"A cache outage can become a database outage if fallback traffic has no admission control."},{"hint":"The authoritative state is in another concurrency system.","lessonID":"sql.isolation-and-locks","nuance":"Isolation levels and lock details are database-specific. Do not promise one engine’s exact behavior for every SQL driver."},{"hint":"Multiply per-process settings by every active pool owner.","lessonID":"sql.pool-lifetime","nuance":"A larger connection cap can move waiting into an overloaded database. Admission and query efficiency still need their own policies."},{"hint":"Distinguish an explicit abort from a missing acknowledgment.","lessonID":"sql.retry-and-idempotency","nuance":"Retry classification is driver-specific. Preserve one total deadline and use durable deduplication for ambiguous side effects."},{"hint":"Next returning false can mean end of rows or an error.","lessonID":"sql.rows-and-context","nuance":"A parameterized tenant value still requires authorization, and LIMIT is not a universal bound on query execution cost."},{"hint":"Context propagation and transaction membership are different contracts.","lessonID":"sql.transaction-owner","nuance":"A transaction does not automatically include pool calls or an external provider. Check commit outcomes and idempotency at the actual boundary."},{"hint":"A second descriptor still refers to the same backing array.","lessonID":"stdlib.borrowed-buffers","nuance":"Clone copies the bytes. Reset does not revoke aliases or promise to overwrite old storage. A channel send also copies a descriptor, so asynchronous consumption needs an ownership protocol."},{"hint":"select on a timer and ctx.Done(). Stop the timer. Return ctx.Err() when cancelled.","lessonID":"stdlib.context","nuance":"Sleep cannot be cancelled. A timer plus select can. Never store a context on a struct."},{"hint":"HandlerFunc. 404 unless the path is /hello, then write hi.","lessonID":"stdlib.http","nuance":"httptest is the real types without a listen. Handler is one method: ServeHTTP."},{"hint":"The body is limited to the allowed bytes plus one detection byte, so a truncated success cannot be mistaken for a complete valid response.","lessonID":"stdlib.http-client-budgets","nuance":"No. Check status, bound time and response bytes, validate parsing and always close the body; retry semantics depend on the operation."},{"hint":"Bounds is image.Rect(0, 0, W, H). At returns C.","lessonID":"stdlib.image","nuance":"image.Image is three methods. A PNG file and your Solid both satisfy it."},{"hint":"ReadAll the reader, write the uppercased string to the writer.","lessonID":"stdlib.io","nuance":"Accept io.Reader and io.Writer, not *os.File. The test passes a buffer on purpose."},{"hint":"The field tag is the name on the wire. Unmarshal needs a pointer.","lessonID":"stdlib.json","nuance":"Unmarshal needs a non-nil pointer; a non-pointer returns InvalidUnmarshalError. omitempty skips zero values, including false and 0."},{"hint":"Duplicate names and unknown names are different cases.","lessonID":"stdlib.json-input-policy","nuance":"Strict decoding cannot authorize a resource or make an external write exactly once."},{"hint":"Ask what a pointer contains after null and after an omitted property.","lessonID":"stdlib.json-presence","nuance":"A tag controls encoding behavior; it does not define authorization, business validation or every partial-update transition."},{"hint":"A new API surface and a new wire representation are separate changes.","lessonID":"stdlib.json-v2-contracts","nuance":"Go compatibility does not imply that selecting different serializer defaults preserves your application protocol."},{"hint":"slices.SortFunc with cmp.Compare on year, then name.","lessonID":"stdlib.sort","nuance":"The comparator returns a number, not a bool. That is the C/Go convention, not JS."},{"hint":"Atoi, then reject n < 1 or n > 65535.","lessonID":"stdlib.strconv","nuance":"Atoi(\"x\") is 0 and an error. Discard the error and you shipped port 0."},{"hint":"Duration constants are multiplications. A bare 5 is five nanoseconds.","lessonID":"stdlib.time","nuance":"Time comparison uses Before, After, Equal — a Time carries a monotonic reading too."},{"hint":"One goroutine creates, resets and receives the timer.","lessonID":"stdlib.timer-contracts","nuance":"No. Ready cases have no source-order priority; define ownership and commit checks explicitly rather than depending on select order."},{"hint":"Declare count inside Counter so each call gets its own.","lessonID":"structs.closures","nuance":"A closure captures the variable, not its value. Two closures over one count share writes."},{"hint":"Returning &local is ordinary Go. The compiler moves it to the heap.","lessonID":"structs.escape","nuance":"There is no dangling stack pointer. Escape analysis is why NewFoo can return &Foo{}."},{"hint":"Use keyed fields. Width and Height, not a positional pair.","lessonID":"structs.literals","nuance":"A positional literal breaks the moment someone inserts a field. The zero fills what you omit."},{"hint":"Add needs a pointer receiver or the increment dies on a copy.","lessonID":"structs.methods","nuance":"A value receiver is a copy. The method compiles, runs, and changes nothing the caller can see."},{"hint":"Take the address when you mean to change the original.","lessonID":"structs.pointers","nuance":"A pointer is for sharing mutation, not for speed. Small structs are passed by value on purpose."},{"hint":"The new reader accepts the old name field and prefers the additive display_name field when present.","lessonID":"systems.compatibility","nuance":"After compatible readers are deployed, data is migrated and evidence shows old consumers no longer require it; rollback and event replay must still work."},{"hint":"Three acknowledgements meet a simple majority threshold for five configured replicas; two do not.","lessonID":"systems.consistency-partitions","nuance":"No. A consistency protocol also needs durable ordering, authority and membership rules; define the guarantee and failure policy of each operation."},{"hint":"Offsets 11 and 13 are complete, but the next safe offset remains 12.","lessonID":"systems.messaging-offsets","nuance":"No. Commit only the next offset after the contiguous durable prefix; otherwise a restart can skip the unfinished record."},{"hint":"The event has a fixed message and named fields, so a reader can search by operation and reason rather than parse prose.","lessonID":"systems.observability","nuance":"Keep high-cardinality identifiers in appropriately protected logs or traces; metrics use a bounded set of operation and outcome labels."},{"hint":"The stable event ID, not a newly generated delivery ID, identifies the duplicate.","lessonID":"systems.outbox-inbox","nuance":"Retry may deliver the event again. A stable ID and an atomic consumer inbox/effect boundary prevent repeating the business effect."},{"hint":"The cancelled context maps to the protocol’s cancellation status.","lessonID":"systems.rpc-contracts","nuance":"No. Define partial-result, durable-effect and resume/idempotency semantics; deadlines and generated types do not provide atomic rollback."},{"hint":"Shipping failure moves the workflow into refunding.","lessonID":"systems.sagas","nuance":"The outcome is unknown. Reconcile the stable payment identity before retrying or compensating, and keep the workflow state durable."},{"hint":"The composite key demonstrates why order ID alone is insufficient when IDs are only unique within a tenant.","lessonID":"systems.tenant-isolation","nuance":"No. The verified tenant scope must participate in lookup and authorization, including the cache key, storage predicate and job context."},{"hint":"The first call validates before changing either account and prints balances 3 and 11.","lessonID":"systems.transaction-boundary","nuance":"The application use case owns one transaction and passes its handle to every participating storage operation; HTTP mapping stays in the adapter."}],"id":"go","labs":[],"practice":{"bugs":[{"brief":"This should print the doubled value. It does not compile.","conceptTag":"vars.unused","explanation":"`doubled` is declared and never used, which is a compile error in Go rather than a warning. The language treats an unused local as a mistake you meant to catch — either print it or do not declare it.","faultyLine":2,"id":"bug.core.unused","lines":["func main() {","\tvalue := 21","\tdoubled := value * 2","\tfmt.Println(value)","}"],"unitID":"core"},{"brief":"This should count words. It panics at run time.","conceptTag":"maps.zero-value","explanation":"A `var` map is nil. Reading from a nil map is fine and gives the zero value, which is why the loop looks safe — but writing to one panics. It needed `make(map[string]int)`.","faultyLine":1,"id":"bug.collections.nil-map","lines":["func count(words []string) map[string]int {","\tvar totals map[string]int","\tfor _, word := range words {","\t\ttotals[word]++","\t}","\treturn totals","}"],"unitID":"collections"},{"brief":"This should add an item to the caller's slice. The caller never sees it.","conceptTag":"slices.capacity","explanation":"append returns a new slice header, and the parameter is a copy of the caller's. Assigning to it changes nothing outside the function. The signature has to return the slice, or take a pointer to it.","faultyLine":1,"id":"bug.collections.append-copy","lines":["func add(items []string, item string) {","\titems = append(items, item)","}","","func main() {","\tnames := []string{\"a\"}","\tadd(names, \"b\")","\tfmt.Println(len(names))","}"],"unitID":"collections"},{"brief":"This should fail loudly when the file is missing. It carries on instead.","conceptTag":"errors.explicit-check","explanation":"The error is discarded with `_`, so a missing file returns an empty slice that looks exactly like an empty file. In Go an error is a value you have to decide about; throwing it away is the decision to pretend nothing went wrong.","faultyLine":1,"id":"bug.errors.ignored","lines":["func load(path string) []byte {","\tdata, _ := os.ReadFile(path)","\treturn data","}"],"unitID":"errors"},{"brief":"This should recognise a missing file. It stops recognising it the moment anybody wraps the error.","conceptTag":"errors.sentinel","explanation":"`==` compares the error you were handed, not the chain inside it. One `%w` between you and the sentinel and the branch stops firing. `errors.Is(err, os.ErrNotExist)` walks the chain, which is what it is for.","faultyLine":1,"id":"bug.errors.comparison","lines":["func handle(err error) {","\tif err == os.ErrNotExist {","\t\tcreate()","\t\treturn","\t}","\tlog.Fatal(err)","}"],"unitID":"errors"},{"brief":"This compiles and runs. `go vet` and every reviewer will still stop on it.","conceptTag":"errors.custom","explanation":"Error strings are lower case and unpunctuated, because they get wrapped: yours ends up in the middle of a longer sentence, and a capital letter there reads as a new one starting.","faultyLine":2,"id":"bug.errors.capital","lines":["func parse(input string) error {","\tif input == \"\" {","\t\treturn errors.New(\"Input was empty\")","\t}","\treturn nil","}"],"unitID":"errors"},{"brief":"This should close each file as it finishes with it. It holds every one of them open instead.","conceptTag":"errors.defer","explanation":"A defer runs when the *function* returns, not when the loop body ends. Over a long list that is every file open at once. The body has to become its own function, or the close has to be called explicitly.","faultyLine":6,"id":"bug.errors.defer-loop","lines":["func readAll(paths []string) {","\tfor _, path := range paths {","\t\tfile, err := os.Open(path)","\t\tif err != nil {","\t\t\tcontinue","\t\t}","\t\tdefer file.Close()","\t\tprocess(file)","\t}","}"],"unitID":"errors"},{"brief":"This should hand three jobs to a worker. It panics somewhere in the middle.","conceptTag":"concurrency.channel-close","explanation":"The receiver closes the channel. Closing means \"no more values are coming\", which only the sender knows — and the next send lands on a closed channel and panics. The sender closes, after its last send.","faultyLine":5,"id":"bug.concurrency.receiver-closes","lines":["func main() {","\tjobs := make(chan int)","\tgo func() {","\t\tfor job := range jobs {","\t\t\tprocess(job)","\t\t\tclose(jobs)","\t\t}","\t}()","\tfor i := 1; i <= 3; i++ {","\t\tjobs <- i","\t}","}"],"unitID":"concurrency"},{"brief":"This should wait for three workers. It sometimes returns before any of them have run.","conceptTag":"concurrency.waitgroup","explanation":"Add runs inside the goroutine, so Wait can be reached while the counter is still zero and return immediately. Add belongs before `go`, on the line that decides there will be another worker.","faultyLine":4,"id":"bug.concurrency.waitgroup-inside","lines":["func main() {","\tvar workers sync.WaitGroup","\tfor i := 0; i < 3; i++ {","\t\tgo func() {","\t\t\tworkers.Add(1)","\t\t\tdefer workers.Done()","\t\t\twork()","\t\t}()","\t}","\tworkers.Wait()","}"],"unitID":"concurrency"},{"brief":"This compiles and works. It still gets sent back in review.","conceptTag":"context.first-parameter","explanation":"A context.Context is the first parameter, always, and it is named ctx. It is a convention rather than a rule, which is exactly why breaking it is noticed: every other function in the codebase reads the other way round.","faultyLine":0,"id":"bug.concurrency.context-position","lines":["func Fetch(url string, ctx context.Context) ([]byte, error) {","\treq, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)","\tif err != nil {","\t\treturn nil, err","\t}","\treturn send(req)","}"],"unitID":"concurrency"},{"brief":"This should print the keys in a stable order. The order changes between runs.","conceptTag":"maps.order","explanation":"Range over a map visits keys in a deliberately randomised order — the runtime randomises it so nobody can depend on one by accident. Collect the keys, sort them, then range over the sorted slice.","faultyLine":1,"id":"bug.stdlib.map-order","lines":["func printKeys(scores map[string]int) {","\tfor name := range scores {","\t\tfmt.Println(name)","\t}","}"],"unitID":"stdlib"},{"brief":"This should return no error when the input is fine. The caller's `err != nil` fires anyway.","conceptTag":"interfaces.nil","explanation":"Returning a typed nil pointer as an error fills the type half of the interface value, and an interface is nil only when both halves are. Return a literal nil on the happy path instead of a typed variable.","faultyLine":5,"id":"bug.interfaces.typed-nil","lines":["func validate(input string) error {","\tvar problem *ValidationError","\tif input == \"\" {","\t\tproblem = &ValidationError{}","\t}","\treturn problem","}"],"unitID":"interfaces"}],"drills":[{"id":"drill.core","pairs":[{"answer":"Declares and infers, inside a function only","conceptTag":"vars.short-declaration","id":"core.short","prompt":"x := 3","promptIsCode":true},{"answer":"A local you named but never read","conceptTag":"vars.unused","id":"core.unused","prompt":"declared and not used","promptIsCode":false},{"answer":"Exists already, holding the zero value \"\"","conceptTag":"vars.short-declaration","id":"core.zero","prompt":"var s string","promptIsCode":true},{"answer":"A path out of the function returns nothing","conceptTag":"functions.missing-return","id":"core.return","prompt":"missing return","promptIsCode":false},{"answer":"An import no line in the file refers to","conceptTag":"modules.unused-import","id":"core.import","prompt":"imported and not used","promptIsCode":false}],"subtitle":"What Go does with a name","title":"Declarations","unitID":"core"},{"id":"drill.slices","pairs":[{"answer":"Allocates a new array; the old one is untouched","conceptTag":"slices.capacity","id":"slices.append","prompt":"append past cap","promptIsCode":false},{"answer":"Shares a backing array; append may detach it","conceptTag":"slices.aliasing","id":"slices.alias","prompt":"b := a[1:3]","promptIsCode":true},{"answer":"Read past len, which is not the same as cap","conceptTag":"slices.capacity","id":"slices.bounds","prompt":"index out of range","promptIsCode":false},{"answer":"The zero value, not an error and not a panic","conceptTag":"maps.zero-value","id":"maps.missing","prompt":"m[\"nope\"]","promptIsCode":true},{"answer":"r is a rune; i counts bytes, not characters","conceptTag":"strings.runes","id":"strings.range","prompt":"for i, r := range s","promptIsCode":true}],"subtitle":"What the header actually holds","title":"Slices and maps","unitID":"collections"},{"id":"drill.interfaces","pairs":[{"answer":"Only *Counter satisfies it, never Counter","conceptTag":"interfaces.method-set","id":"iface.pointer","prompt":"func (c *Counter) Add()","promptIsCode":true},{"answer":"A nil pointer inside a non-nil interface value","conceptTag":"interfaces.nil","id":"iface.nil","prompt":"err != nil, but err is nil","promptIsCode":false},{"answer":"One method is easier to satisfy than five","conceptTag":"interfaces.size","id":"iface.small","prompt":"interface { Read(...) }","promptIsCode":true},{"answer":"Take what you need; return what you built","conceptTag":"interfaces.size","id":"iface.accept","prompt":"Accept interfaces","promptIsCode":false}],"subtitle":"Who satisfies what","title":"Interfaces","unitID":"interfaces"},{"id":"drill.errors","pairs":[{"answer":"The check Go asks for at every call that can fail","conceptTag":"errors.explicit-check","id":"errors.check","prompt":"if err != nil","promptIsCode":true},{"answer":"Adds context and keeps the original reachable","conceptTag":"errors.wrapping","id":"errors.wrap","prompt":"fmt.Errorf(\"...: %w\", err)","promptIsCode":true},{"answer":"Compares against a known error, through wrapping","conceptTag":"errors.sentinel","id":"errors.sentinel","prompt":"errors.Is(err, io.EOF)","promptIsCode":true},{"answer":"Runs when the function returns, however it returns","conceptTag":"errors.defer","id":"errors.defer","prompt":"defer f.Close()","promptIsCode":true}],"subtitle":"Values, not exceptions","title":"Errors","unitID":"errors"},{"id":"drill.concurrency","pairs":[{"answer":"A rendezvous: send waits for a receiver","conceptTag":"concurrency.deadlock","id":"conc.unbuffered","prompt":"make(chan int)","promptIsCode":true},{"answer":"The sender's job, and only ever once","conceptTag":"concurrency.channel-close","id":"conc.close","prompt":"close(ch)","promptIsCode":true},{"answer":"Takes the ready branch, or gives up at once","conceptTag":"concurrency.select","id":"conc.select","prompt":"select with default","promptIsCode":false},{"answer":"First parameter, never stored in a struct","conceptTag":"context.first-parameter","id":"conc.ctx","prompt":"ctx context.Context","promptIsCode":true},{"answer":"Add outside the goroutine, Done inside it","conceptTag":"concurrency.waitgroup","id":"conc.wg","prompt":"wg.Add before go","promptIsCode":false},{"answer":"Blocks on send forever and is never collected","conceptTag":"concurrency.goroutine-leak","id":"conc.leak","prompt":"A goroutine nobody reads","promptIsCode":false}],"subtitle":"What blocks, and until when","title":"Concurrency","unitID":"concurrency"},{"id":"drill.stdlib","pairs":[{"answer":"One method, and half the library accepts it","conceptTag":"stdlib.io","id":"std.io","prompt":"io.Reader","promptIsCode":true},{"answer":"Fills a value you pass by pointer","conceptTag":"stdlib.json","id":"std.json","prompt":"json.Unmarshal","promptIsCode":true},{"answer":"A subtest that can fail on its own","conceptTag":"stdlib.testing","id":"std.testing","prompt":"t.Run(name, func)","promptIsCode":true},{"answer":"Reads a stream a line at a time","conceptTag":"stdlib.io","id":"std.bufio","prompt":"bufio.Scanner","promptIsCode":true}],"subtitle":"Reach for these first","title":"Standard library","unitID":"stdlib"}],"interviews":[{"answerPoints":["Every type has a zero value and every declaration produces it: 0, \"\", false, nil for pointers, slices, maps, channels and interfaces, and a struct whose fields are each their own zero.","Every declaration is initialized, but allowed operations still depend on the type: append works on a nil slice, assigning a nil map panics, and a nil-channel send blocks. Types that require configuration must make that requirement explicit.","The exchange is that the zero value has to be designed. sync.Mutex and bytes.Buffer are usable at zero; a type that needs setup has to say so, which is why NewThing exists as a convention rather than a language feature."],"code":"","conceptTag":"vars.short-declaration","id":"interview.core.zero-values","prompt":"Go has no constructors and no uninitialised memory. What is a zero value, and what does the language get in exchange for insisting on one?","trap":"Saying it is \"like default initialisation in C++ or Java\". Those languages leave some things uninitialised or require a constructor to run; Go's point is that neither is ever true.","unitID":"core"},{"answerPoints":["When the method mutates the receiver, because a value receiver mutates a copy and the caller sees nothing.","When the value is large enough that copying it per call matters — though that is a measurement, not a guess.","Prefer a consistent receiver convention when a type needs mutation or must not be copied. This is design guidance, not a language rule: T and *T have different method sets, and some mixed receiver APIs can be deliberate."],"code":"","conceptTag":"interfaces.method-set","id":"interview.core.receivers","prompt":"When do you give a method a pointer receiver rather than a value receiver?","trap":"\"Pointers are faster.\" For a small struct a copy is often cheaper than the indirection, and the real reason is mutation, not speed.","unitID":"core"},{"answerPoints":["A slice is a pointer to an array, a length and a capacity. Length is how many elements you can index; capacity is how many the underlying array has from that pointer onwards.","append writes in place while length is below capacity. When it is not, it allocates a bigger array, copies, and returns a slice pointing at the new one.","That is why the return value of append must be used: after a growth the old slice header is stale."],"code":"","conceptTag":"slices.capacity","id":"interview.collections.append","prompt":"What is the difference between a slice's length and its capacity, and when does append allocate?","trap":"Saying append \"always allocates\" or \"never does\". Which one happened is invisible from the call site, which is exactly why the result has to be assigned.","unitID":"collections"},{"answerPoints":["left has room in the shared array, so append writes index 2 in place rather than allocating.","right[2] is that same element, so it now reads 99 — nothing was copied and nothing warned you.","Cutting the capacity with a three-index slice, base[0:2:2], makes the append allocate instead and breaks the aliasing on purpose."],"code":"base := make([]int, 3, 8)\nleft := base[0:2]\nright := base[0:3]\nleft = append(left, 99)","conceptTag":"slices.aliasing","id":"interview.collections.aliasing","prompt":"Two slices are taken from the same array. What happens to the second when you append to the first?","trap":"Assuming a slice expression copies. It never does: it makes another view of the same array.","unitID":"collections"},{"answerPoints":["Structurally and implicitly: a type satisfies an interface by having the methods, with no declaration that it intends to.","It is checked at compile time, at the point of assignment or call — not at run time, and not where the type is defined.","So an interface can be declared by the consumer, next to the code that needs it, and existing types satisfy it without being touched. That is why Go interfaces are usually small and defined where they are used."],"code":"","conceptTag":"interfaces.size","id":"interview.interfaces.satisfaction","prompt":"How does a type come to satisfy an interface in Go, and when is that decided?","trap":"Reaching for \"duck typing\". The checking is static; nothing is discovered at run time.","unitID":"interfaces"},{"answerPoints":["An interface value is a pair: a type and a value. It is nil only when both halves are.","Returning a nil *NotFoundError as an error fills the type half, so the interface is not nil even though the pointer is.","The fix is to return a literal nil rather than a typed nil variable — and to not declare a typed error variable for the happy path in the first place."],"code":"func find() error {\n\tvar err *NotFoundError\n\treturn err\n}","conceptTag":"interfaces.nil","id":"interview.interfaces.nil","prompt":"A function returns an error that is not nil, but the pointer inside it is. How does that happen?","trap":"\"err == nil should be true because err is nil.\" It is the most reliably surprising thing in the language, and the answer is that the comparison is about the pair.","unitID":"interfaces"},{"answerPoints":["Wrap with %w when you are adding context the caller does not have — which file, which key, which request — and the original still matters for a decision further up.","Return it unchanged when you have nothing to add. A wrap that says \"failed to read: failed to read: no such file\" is noise.","Do not wrap when the original is an implementation detail you do not want callers matching on: that turns a private failure into part of your API."],"code":"","conceptTag":"errors.wrapping","id":"interview.errors.wrapping","prompt":"When do you wrap an error, and when do you return it as it is?","trap":"Wrapping everything by reflex. Every %w is a promise that callers may use errors.Is against what is inside.","unitID":"errors"},{"answerPoints":["errors.Is asks whether an error in the chain is a particular value — a sentinel such as io.EOF or os.ErrNotExist.","errors.As asks whether an error in the chain is a particular type, and if so assigns it to your variable so you can read its fields.","Both walk the wrap chain, which is why == fails on a wrapped error and errors.Is does not."],"code":"","conceptTag":"errors.sentinel","id":"interview.errors.is-as","prompt":"What is the difference between errors.Is and errors.As?","trap":"Comparing with == out of habit. It works right up until somebody adds a %w between you and the sentinel.","unitID":"errors"},{"answerPoints":["go.mod records the module path and the minimum version your build needs. Go picks the highest minimum across the whole graph — minimal version selection — so a build is reproducible without a lock file.","go.sum records a cryptographic hash of each module's content, so a version that changed underneath you fails verification instead of building.","They answer different questions: go.mod is which version, go.sum is whether the bytes are the ones everybody else got."],"code":"","conceptTag":"modules.import-path","id":"interview.modules.go-sum","prompt":"What does a require line in go.mod pin, and what does go.sum add on top of it?","trap":"Calling go.sum a lock file. It does not choose versions; it verifies whatever was chosen.","unitID":"modules"},{"answerPoints":["The sender closes, because closing means \"no more values are coming\" and only the sending side knows that.","A receiver that closes can race with a send in flight, and a send on a closed channel panics — it is not an error you can handle at the send.","With several senders, nobody closes directly: a WaitGroup waits for them and one goroutine closes afterwards."],"code":"","conceptTag":"concurrency.channel-close","id":"interview.concurrency.close","prompt":"Who closes a channel, and what goes wrong when the other side does it?","trap":"\"Whoever finishes first closes it.\" Closing is not cleanup; it is a message, and it can only be sent by the side that has the news.","unitID":"concurrency"},{"answerPoints":["A mutex protects state several goroutines share: a counter, a cache, a map. The value stays where it is and access is serialised.","A channel hands a value over: one goroutine is finished with it and another should have it. Ownership moves.","If routing something through a channel would just be ceremony around an increment, it is a mutex. If two goroutines are passing work along, it is a channel."],"code":"","conceptTag":"concurrency.mutex","id":"interview.concurrency.mutex-or-channel","prompt":"Mutex or channel — how do you choose?","trap":"\"Share memory by communicating, so always use a channel.\" The proverb is advice about design, not a ban on sync — the standard library is full of mutexes.","unitID":"concurrency"},{"answerPoints":["A goroutine blocked on a channel nobody will ever send to, or on a receive from a context that is never cancelled. It is not an error anywhere: it simply stops, holding its stack.","It shows as memory that climbs and never comes back, and as a goroutine count that only goes up — runtime.NumGoroutine, or the goroutine profile from net/http/pprof.","The fixes are structural: give every goroutine a way to be told to stop, usually a context, and make sure every channel it might block on either gets closed or gets a select with a cancellation branch."],"code":"","conceptTag":"concurrency.goroutine-leak","id":"interview.concurrency.leak","prompt":"What is a goroutine leak, and how would you notice one in production?","trap":"Expecting the runtime to complain. It only reports a deadlock when *every* goroutine is asleep — one stuck goroutine beside a busy program is silent.","unitID":"concurrency"},{"answerPoints":["Its Done channel is closed. That is the whole mechanism — cancellation is a closed channel, which is why a select can wait on it and why it can be observed by any number of goroutines at once.","Cancellation propagates down to contexts derived from it, never up.","Nothing is stopped for you. A goroutine that never checks Done keeps running; the context only makes it possible to notice."],"code":"","conceptTag":"context.cancel","id":"interview.concurrency.context","prompt":"What actually happens when you cancel a context?","trap":"Believing cancel() kills anything. Go has no way to stop another goroutine — cancellation is a request that has to be read.","unitID":"concurrency"},{"answerPoints":["A Read may return data and an error in the same call — n bytes were genuinely read even if err is io.EOF.","So the caller processes the first n bytes before looking at err, in that order. Checking the error first and returning loses data.","io.EOF is not a failure: it is how a reader says it has finished. Any other error is."],"code":"","conceptTag":"stdlib.io","id":"interview.stdlib.reader","prompt":"io.Reader returns (n int, err error). Why both, and what must a caller do with them?","trap":"Treating a non-nil error as \"nothing was read\". That is true of most APIs and not of this one, which is why the interface is worth asking about.","unitID":"stdlib"}],"quizzes":[{"questions":[{"code":"count := 0","conceptTag":"vars.short-declaration","correctIndex":1,"explanation":"Short declaration is function-scoped. At package level you must write var count = 0.","id":"core.q.short","options":["Anywhere a var declaration can","Inside a function only","At package level only","Only inside a for or if statement"],"prompt":"Where can this line appear?"},{"code":"func main() {\n\thost := \"localhost\"\n\tfmt.Println(\"started\")\n}","conceptTag":"vars.unused","correctIndex":2,"explanation":"An unused local is an error in Go, not a warning. Unused imports are the same. There is no flag to soften it.","id":"core.q.unused","options":["Nothing — it compiles","A warning about an unused variable","declared and not used: host","cannot use host as type string"],"prompt":"What does the compiler say?"},{"code":"var s string","conceptTag":"vars.short-declaration","correctIndex":1,"explanation":"Every Go value starts at its zero value. For a string that is \"\", for a pointer nil, for an int 0. There is no uninitialised memory.","id":"core.q.zero","options":["nil","An empty string","Undefined until assigned","A compile error — it needs a value"],"prompt":"What is the value of s?"},{"code":"value, err := strconv.Atoi(\"12x\")","conceptTag":"errors.explicit-check","correctIndex":0,"explanation":"Ordinary Go failures are returned as error values. A fallible function returns an error beside its result, and the caller decides what to do about it.","id":"core.q.multiple","options":["To avoid exceptions: failure is a value you must handle","Because Atoi is generic","The second value is always ignored","To make the function faster"],"prompt":"Why does Go return two values here?"},{"code":"","conceptTag":"modules.unused-import","correctIndex":2,"explanation":"Same rule as an unused variable: it is an error. If you need the import only for its side effects, write _ \"os\".","id":"core.q.import","options":["Nothing — unused imports are ignored","The linker drops it silently","imported and not used: \"os\"","A warning, but it still builds"],"prompt":"The file imports \"os\" but never mentions os again. What happens?"},{"code":"func Split(n, d int) (quot, rem int) {\n\tquot = n / d\n\trem = n % d\n\treturn\n}","conceptTag":"functions.named-results","correctIndex":3,"explanation":"The names in the result list are variables. A return with no arguments sends those. The Tour says keep that for short functions.","id":"core.q.named","options":["Always 0, 0","A compile error — return needs values","Whatever is in scope named x, y","The named results as they stand"],"prompt":"What does a naked return send?"}],"title":"Go core","unitID":"core"},{"questions":[{"code":"p := Point{X: 1, Y: 2}\nq := Point{1, 2}","conceptTag":"types.struct-literal","correctIndex":2,"explanation":"A keyed literal names the fields it supplies, so adding a field does not change those names. Omitted fields take their zero values. A positional literal must supply every field in declaration order.","id":"structs.q.literal","options":["It is faster to compile","It is the only form vet accepts","It survives a field being added","Positional literals can leave any fields out"],"prompt":"Why is the named form preferred for a struct literal?"},{"code":"func (r Rect) Grow() { r.Width++ }","conceptTag":"types.pointer","correctIndex":0,"explanation":"A value receiver is a copy. The method compiles, runs and mutates the copy, and nothing warns you that the change went nowhere.","id":"structs.q.receiver","options":["Nothing; it changed a copy","The increment, as normal","A compile error","A panic at run time"],"prompt":"Grow has a value receiver and increments a field. What does the caller see?"},{"code":"type Point struct{ X, Y int }","conceptTag":"types.struct-literal","correctIndex":3,"explanation":"A struct is never nil. Its zero value has every field at that field's own zero, and the variable is usable straight away.","id":"structs.q.zero","options":["nil, until it is made","Undefined memory","A compile error until initialised","A struct with X and Y at 0"],"prompt":"What is `var p Point` before anything is assigned to it?"},{"code":"func New() *Config {\n\tc := Config{}\n\treturn &c\n}","conceptTag":"types.pointer","correctIndex":0,"explanation":"Escape analysis notices the value outlives the call and allocates it where it survives. This is ordinary Go — every New... does it.","id":"structs.q.escape","options":["It compiles; the value escapes","A dangling pointer at run time","A compile error","It works only for small types"],"prompt":"A function returns the address of a local variable. What happens?"},{"code":"count := 0\nup := func() { count++ }\nread := func() int { return count }","conceptTag":"functions.closure","correctIndex":1,"explanation":"A closure captures the variable, not its value, so writes made through one are visible through the other.","id":"structs.q.closure","options":["Nothing; each copies it","The variable itself","Only its value at capture","Nothing until they are called"],"prompt":"What do two closures over the same variable share?"}],"title":"Types you define","unitID":"structs"},{"questions":[{"code":"a := []int{1, 2, 3, 4}\nb := a[1:3]\nb[0] = 99\nfmt.Println(a)","conceptTag":"slices.aliasing","correctIndex":1,"explanation":"Reslicing does not copy. b shares a's backing array, so writing through b writes through a — until an append outgrows cap.","id":"coll.q.alias","options":["[1 2 3 4]","[1 99 3 4]","[99 2 3 4]","[1 99 3]"],"prompt":"What does this print?"},{"code":"b = append(b, 100)","conceptTag":"slices.capacity","correctIndex":2,"explanation":"Inside cap it writes in place and the sharing stays. Past cap it allocates a new array, and the two slices quietly stop being connected.","id":"coll.q.append","options":["Always — append always copies","Never — append always writes in place","When the result would exceed cap(b)","When len(b) is odd"],"prompt":"When does append stop writing into the original array?"},{"code":"n := scores[\"nope\"]","conceptTag":"maps.zero-value","correctIndex":2,"explanation":"Reading a missing key gives the zero value. Use the two-value form, n, ok := scores[\"nope\"], when absent and zero mean different things.","id":"coll.q.map","options":["A panic","An error value","The zero value for the map's type","nil, whatever the type"],"prompt":"The map has no key \"nope\". What does this give?"},{"code":"","conceptTag":"strings.runes","correctIndex":1,"explanation":"len counts bytes. é is two bytes in UTF-8. Range over the string, or convert to []rune, to count characters.","id":"coll.q.len","options":["5","6","10","It depends on the locale"],"prompt":"What is len(\"héllo\")?"},{"code":"","conceptTag":"strings.runes","correctIndex":1,"explanation":"i is a byte offset, so it jumps by more than one for multi-byte characters. r is the rune itself.","id":"coll.q.range","options":["The character's position","The byte offset of the character","Always the same as the loop count","The rune's Unicode code point"],"prompt":"In for i, r := range s, what is i?"},{"code":"func Sum(a [4]int) int\nSum([3]int{1, 2, 3})","conceptTag":"types.array","correctIndex":0,"explanation":"The length is in the type. The Tour's Arrays page is the one people skip, then a [32]byte parameter refuses a [16]byte.","id":"coll.q.array","options":["[3]int and [4]int are different types","Arrays cannot be passed to functions","The literal needs a ...","Sum must take a slice"],"prompt":"Why will this not compile?"},{"code":"double := func(n int) int { return n * 2 }","conceptTag":"functions.value","correctIndex":3,"explanation":"The Tour: functions are values. The type includes the arguments and the result. func(int) int is not the same as func(int) string.","id":"coll.q.funcval","options":["int","func","closure","func(int) int"],"prompt":"What is the type of this value?"}],"title":"Slices, maps and strings","unitID":"collections"},{"questions":[{"code":"type Adder interface{ Add() }\nfunc (c *Counter) Add() { c.n++ }","conceptTag":"interfaces.method-set","correctIndex":1,"explanation":"A pointer receiver puts the method in *Counter's method set only. A value receiver would put it in both.","id":"iface.q.methodset","options":["Both","*Counter","Counter","Neither"],"prompt":"Add is declared on *Counter. Which type satisfies Adder?"},{"code":"var p *MyError = nil\nvar err error = p\nif err != nil { fmt.Println(\"not nil\") }","conceptTag":"interfaces.nil","correctIndex":1,"explanation":"An interface is nil only when both its type and its value are. Return a bare nil rather than a typed nil pointer.","id":"iface.q.nil","options":["Because p was never assigned","The interface holds a type and a value; only the value is nil","Because MyError does not implement error","It does not — this prints nothing"],"prompt":"Why does this print \"not nil\"?"},{"code":"","conceptTag":"interfaces.size","correctIndex":2,"explanation":"io.Reader is one method, and half the standard library accepts it. The larger the interface, the fewer things can be passed to you.","id":"iface.q.small","options":["One with five methods, so it is complete","One that embeds three others","One with a single method","It makes no difference"],"prompt":"Which interface is easier for callers to satisfy?"},{"code":"","conceptTag":"interfaces.size","correctIndex":0,"explanation":"The consumer knows what it needs. Declaring it there keeps the interface as small as the use, and implementers need not import anything.","id":"iface.q.accept","options":["In the package that consumes it","In the package that implements it","In a shared interfaces package","Anywhere — it makes no difference"],"prompt":"Where should an interface usually be declared?"},{"code":"type IPAddr [4]byte","conceptTag":"fmt.stringer","correctIndex":3,"explanation":"The Tour's Stringers page: fmt.Stringer is String() string. Nothing registers. Do not Sprint the value from its own String.","id":"iface.q.stringer","options":["A String() keyword on the type","Registering it with fmt","Implementing encoding.TextMarshaler only","A String() method; fmt looks for it"],"prompt":"How does fmt print a type as a dotted IP?"}],"title":"Interfaces","unitID":"interfaces"},{"questions":[{"code":"type Number interface{ ~int | ~float64 }","conceptTag":"generics.constraint","correctIndex":3,"explanation":"~float64 means any type whose underlying type is float64, so `type Celsius float64` is admitted. Without it, only float64 itself is.","id":"generics.q.tilde","options":["It makes the type optional","It allows pointers to them","It marks the default type","It admits named types too"],"prompt":"What does the ~ add to a constraint?"},{"code":"func A[T any](v T)\nfunc B(v interface{})","conceptTag":"generics.type-parameter","correctIndex":0,"explanation":"A gets the caller's actual type, so its result stays typed and mistakes are compile errors. B gets a value the caller must assert out of.","id":"generics.q.any","options":["A keeps the caller's type","They are identical","B is checked at compile time","A is slower to call"],"prompt":"How does `any` as a constraint differ from interface{} as a parameter?"},{"code":"func (s *Stack[T]) Map[U any](f func(T) U) []U","conceptTag":"generics.type-parameter","correctIndex":2,"explanation":"Methods repeat the type's parameters but cannot add new ones, which is why Map is a function in every Go library and a method in none.","id":"generics.q.method","options":["Yes, like a function","Only if the receiver is a value","No; it must be a function","Only with a constraint"],"prompt":"Can a method introduce a type parameter of its own?"},{"code":"func Pop[T any]() (T, bool)","conceptTag":"generics.type-parameter","correctIndex":1,"explanation":"T might be a string or an int, for which nil is not a value, and T{} is not valid for every type. A declared variable is the zero of whatever T turned out to be.","id":"generics.q.zero","options":["return nil, false","var zero T; return zero, false","return T{}, false","return *new(T), false only"],"prompt":"How do you return the zero value of a type parameter T?"},{"code":"func Print[T Stringer](v T) { fmt.Println(v.String()) }","conceptTag":"generics.overuse","correctIndex":3,"explanation":"Nothing here needs the concrete type: no container to keep typed, no operator, no second type. The plain interface parameter says the same thing and reads once instead of twice.","id":"generics.q.overuse","options":["Keep it; it avoids dispatch","Add a second type parameter","Drop the constraint for any","Take the interface as a parameter"],"prompt":"The constraint is an interface with one method and nothing else. Now what?"}],"title":"Generics","unitID":"generics"},{"questions":[{"code":"","conceptTag":"errors.wrapping","correctIndex":1,"explanation":"%w wraps: errors.Is and errors.As can still see through it. %v formats it into a string and the original is gone.","id":"err.q.wrap","options":["fmt.Errorf(\"load: %v\", err)","fmt.Errorf(\"load: %w\", err)","errors.New(\"load: \" + err.Error())","Both %v and %w"],"prompt":"Which keeps the original error reachable?"},{"code":"","conceptTag":"errors.sentinel","correctIndex":1,"explanation":"errors.Is unwraps. A direct == fails the moment anyone adds context with %w, and comparing strings breaks on a reworded message.","id":"err.q.is","options":["err == io.EOF","errors.Is(err, io.EOF)","err.Error() == \"EOF\"","reflect.TypeOf(err) == reflect.TypeOf(io.EOF)"],"prompt":"How should a caller test for a known error?"},{"code":"f, err := os.Open(name)\nif err != nil { return err }\ndefer f.Close()","conceptTag":"errors.defer","correctIndex":1,"explanation":"Function scope, not block scope, and it runs on a panic too. That is what makes it the right place for cleanup.","id":"err.q.defer","options":["At the end of the enclosing block","When the function returns, however it returns","Only on a normal return, not on a panic","Immediately, on the next line"],"prompt":"When does the deferred call run?"},{"code":"value, _ := strconv.Atoi(input)","conceptTag":"errors.explicit-check","correctIndex":2,"explanation":"On failure Atoi returns 0 and an error. Discarding the error turns bad input into a plausible-looking zero, which is the hardest bug to find.","id":"err.q.ignore","options":["Nothing, if you are sure input is a number","It will not compile","A failure silently becomes 0","Atoi never returns an error"],"prompt":"What is wrong with this?"},{"code":"","conceptTag":"errors.panic","correctIndex":0,"explanation":"recover is nil unless it is called from a function deferred on the panicking goroutine. A named result is how the error gets out.","id":"err.q.recover","options":["Inside a deferred function","On the next line after panic","In main, always","Anywhere in the same goroutine"],"prompt":"Where does recover actually work?"}],"title":"Errors","unitID":"errors"},{"questions":[{"code":"func main() {\n\tch := make(chan int)\n\tch <- 1\n\tfmt.Println(<-ch)\n}","conceptTag":"concurrency.deadlock","correctIndex":1,"explanation":"An unbuffered channel is a rendezvous: the send waits for a receiver, and the only goroutine that could receive is the one sending.","id":"conc.q.deadlock","options":["It prints 1","fatal error: all goroutines are asleep - deadlock!","It prints 0","It blocks forever with no message"],"prompt":"What happens when this runs?"},{"code":"","conceptTag":"concurrency.channel-close","correctIndex":1,"explanation":"Closing tells receivers there is no more. A receiver cannot know that, and closing twice — or sending after a close — panics.","id":"conc.q.close","options":["The receiver, when it has had enough","The sender, and only once","Whichever finishes first","Nobody — the runtime does it"],"prompt":"Who should close a channel?"},{"code":"","conceptTag":"concurrency.select","correctIndex":2,"explanation":"With a default, select never blocks. Without one, it waits for the first branch that becomes ready.","id":"conc.q.select","options":["Runs when every other case is ready","Runs last, always","Makes select return at once when nothing is ready","Repeats the select until a case fires"],"prompt":"What does a default case do in a select?"},{"code":"for _, job := range jobs {\n\t???\n\tgo worker(job)\n}","conceptTag":"concurrency.waitgroup","correctIndex":1,"explanation":"Add inside the goroutine races with Wait, which may see a counter of zero and return before anything started.","id":"conc.q.wg","options":["Inside the goroutine, first line","Before starting the goroutine","After the loop, once, with the total","It makes no difference"],"prompt":"Where does wg.Add(1) belong?"},{"code":"go func() { results <- expensive() }()","conceptTag":"concurrency.goroutine-leak","correctIndex":1,"explanation":"A goroutine blocked on a channel nobody reads is a leak: it holds its stack and everything it references, for the life of the program.","id":"conc.q.leak","options":["It is garbage collected","It blocks on the send forever and is never collected","The send fails with an error","It panics"],"prompt":"The receiver returned early. What happens to this goroutine?"},{"code":"","conceptTag":"context.first-parameter","correctIndex":1,"explanation":"First parameter, never stored. A stored context outlives the call it belonged to, and cancelling it then means nothing.","id":"conc.q.ctx","options":["Stored in the struct that needs it","As the first parameter, named ctx","In a package-level variable","Anywhere in the parameter list"],"prompt":"Where does a context belong?"},{"code":"","conceptTag":"concurrency.buffered","correctIndex":0,"explanation":"The Tour: sends block when the buffer is full, receives when it is empty. A buffer of 1 is a mailbox of one, not a queue without a lid.","id":"conc.q.buffer","options":["When the one slot is already full","Always — a buffer is only a hint","Never — buffered sends never wait","Only from the main goroutine"],"prompt":"When does a send on make(chan int, 1) block?"},{"code":"","conceptTag":"concurrency.once","correctIndex":3,"explanation":"Do runs f once for that Once, even across goroutines. A different f on the second call is ignored. Do not copy the Once after first use.","id":"conc.q.once","options":["Runs f again","Runs a new function if you pass one","Panics","Nothing — f already ran"],"prompt":"What does once.Do(f) do on the second call?"}],"title":"Concurrency","unitID":"concurrency"},{"questions":[{"code":"","conceptTag":"modules.import-path","correctIndex":0,"explanation":"A directory is a package. Every file in it shares one package clause, and two different clauses in one directory is an error.","id":"mod.q.dir","options":["Its directory","Its file name","The order of imports","The go.mod file"],"prompt":"What decides which package a file belongs to?"},{"code":"","conceptTag":"modules.import-path","correctIndex":1,"explanation":"internal/ is enforced by the compiler: only code rooted at its parent may import it. It is how a module keeps an implementation private.","id":"mod.q.internal","options":["Anyone who knows the path","Only code inside example.com/app","Only the package that declares it","Nobody — internal is not importable"],"prompt":"Who can import example.com/app/internal/store?"},{"code":"","conceptTag":"modules.import-path","correctIndex":2,"explanation":"Case is the visibility rule. Message is exported, message is not, and there is no third level.","id":"mod.q.export","options":["An export keyword","Declaring it at package level","A capital first letter","Listing it in go.mod"],"prompt":"What makes an identifier visible outside its package?"},{"code":"module example.com/app","conceptTag":"modules.import-path","correctIndex":1,"explanation":"The module path prefixes every import inside it: the directory greet becomes example.com/app/greet.","id":"mod.q.path","options":["It must be a real URL that resolves","It is the prefix every package in the module is imported by","It only names the folder","It picks the Go version"],"prompt":"What is the module path in go.mod for?"}],"title":"Modules and packages","unitID":"modules"},{"questions":[{"code":"","conceptTag":"stdlib.io","correctIndex":0,"explanation":"Read, and nothing else. That is why a file, a network connection and a string can all be passed to the same function.","id":"std.q.reader","options":["One","Two","Three","It depends on the implementation"],"prompt":"How many methods does io.Reader have?"},{"code":"json.Unmarshal(data, &value)","conceptTag":"stdlib.json","correctIndex":1,"explanation":"Go passes everything by value. Without the pointer, Unmarshal would fill a copy and the caller would see nothing change.","id":"std.q.json","options":["For speed","So it can fill a value the caller owns","Because JSON is always an object","It does not — that & is optional"],"prompt":"Why does Unmarshal take a pointer?"},{"code":"t.Run(name, func(t *testing.T) { ... })","conceptTag":"stdlib.testing","correctIndex":1,"explanation":"Each case reports separately, so one failure does not hide the rest, and -run can select a single case by name.","id":"std.q.subtest","options":["A faster test","A subtest that can fail on its own and be run by name","A parallel test, always","A benchmark"],"prompt":"What does t.Run give you?"},{"code":"for scanner.Scan() { ... }","conceptTag":"stdlib.io","correctIndex":1,"explanation":"Scan returns false for both EOF and failure. Err() afterwards is the only thing that tells them apart.","id":"std.q.scanner","options":["Scan returns false only at EOF","Check scanner.Err() afterwards","Scan panics on an error","Errors are printed automatically"],"prompt":"The loop ended. How do you know it was not an error?"},{"code":"","conceptTag":"stdlib.http","correctIndex":3,"explanation":"ServeHTTP(ResponseWriter, *Request). HandlerFunc turns a function into that type. httptest exercises it without a listen.","id":"std.q.handler","options":["Three — Get, Post, Serve","Two — ServeHTTP and Listen","It depends on ServeMux","One — ServeHTTP"],"prompt":"How many methods does http.Handler have?"},{"code":"","conceptTag":"stdlib.strconv","correctIndex":2,"explanation":"The Tour's Errors page uses Atoi for this: failure is a value. Ignoring the error turns \"x\" into a plausible zero.","id":"std.q.atoi","options":["A panic","0 and no error","0 and an error","nil"],"prompt":"What does strconv.Atoi(\"x\") return?"}],"title":"Standard library","unitID":"stdlib"}],"reviewPairs":[{"answer":"Stops after the first matching case","conceptTag":"control.switch","id":"review.lesson.core.switch","prompt":"switch without fallthrough","promptIsCode":true,"requiredLessonID":"core.switch"},{"answer":"An explicit conversion; it may discard a fraction","conceptTag":"types.conversion","id":"review.lesson.core.conversions","prompt":"int(x)","promptIsCode":true,"requiredLessonID":"core.conversions"},{"answer":"second runs before first when the function returns","conceptTag":"errors.defer","id":"review.lesson.core.defer-stack","prompt":"defer first(); defer second()","promptIsCode":true,"requiredLessonID":"core.defer-stack"},{"answer":"Keeps access to variables from its surrounding scope","conceptTag":"functions.closure","id":"review.lesson.structs.closures","prompt":"A closure","promptIsCode":false,"requiredLessonID":"structs.closures"},{"answer":"Safe: Go keeps the referenced value alive","conceptTag":"types.pointer","id":"review.lesson.structs.escape","prompt":"return &local","promptIsCode":true,"requiredLessonID":"structs.escape"},{"answer":"i must be below len(s), even when cap(s) is larger","conceptTag":"slices.bounds","id":"review.lesson.collections.bounds","prompt":"s[i]","promptIsCode":true,"requiredLessonID":"collections.bounds"},{"answer":"Its iteration order is unspecified","conceptTag":"maps.order","id":"review.lesson.collections.map-order","prompt":"range over a map","promptIsCode":false,"requiredLessonID":"collections.map-order"},{"answer":"Accumulates text without rebuilding the whole string","conceptTag":"strings.builder","id":"review.lesson.collections.strings-builder","prompt":"strings.Builder","promptIsCode":true,"requiredLessonID":"collections.strings-builder"},{"answer":"ok distinguishes a missing key from a stored zero","conceptTag":"maps.comma-ok","id":"review.lesson.collections.map-ok","prompt":"value, ok := m[key]","promptIsCode":true,"requiredLessonID":"collections.map-ok"},{"answer":"Works; keep the returned slice","conceptTag":"slices.capacity","id":"review.lesson.collections.nil-slice","prompt":"append(nilSlice, value)","promptIsCode":true,"requiredLessonID":"collections.nil-slice"},{"answer":"Can be stored, passed and called like other values","conceptTag":"functions.value","id":"review.lesson.collections.function-values","prompt":"A function value","promptIsCode":false,"requiredLessonID":"collections.function-values"},{"answer":"*T includes value and pointer receiver methods","conceptTag":"interfaces.method-set","id":"review.lesson.interfaces.method-sets","prompt":"T versus *T method sets","promptIsCode":false,"requiredLessonID":"interfaces.method-sets"},{"answer":"Reports a failed assertion without panicking","conceptTag":"types.assertion","id":"review.lesson.interfaces.type-switch","prompt":"v, ok := x.(int)","promptIsCode":true,"requiredLessonID":"interfaces.type-switch"},{"answer":"Promotes methods; it does not add virtual dispatch","conceptTag":"types.embedding","id":"review.lesson.interfaces.embedding","prompt":"An embedded type","promptIsCode":false,"requiredLessonID":"interfaces.embedding"},{"answer":"T is a type argument checked at compile time","conceptTag":"generics.type-parameter","id":"review.lesson.generics.type-parameters","prompt":"func Keep[T any](in []T)","promptIsCode":true,"requiredLessonID":"generics.type-parameters"},{"answer":"Allows types with either of those underlying types","conceptTag":"generics.constraint","id":"review.lesson.generics.constraints","prompt":"~int | ~float64","promptIsCode":true,"requiredLessonID":"generics.constraints"},{"answer":"A generic container instantiated for strings","conceptTag":"generics.type-parameter","id":"review.lesson.generics.containers","prompt":"Stack[string]","promptIsCode":true,"requiredLessonID":"generics.containers"},{"answer":"Fits behavior described only by a set of methods","conceptTag":"generics.overuse","id":"review.lesson.generics.when-not-to","prompt":"An ordinary interface parameter","promptIsCode":false,"requiredLessonID":"generics.when-not-to"},{"answer":"Names a type for that method's inputs or results","conceptTag":"generic-method","id":"review.lesson.generics.methods","prompt":"A method's type parameter","promptIsCode":false,"requiredLessonID":"generics.methods"},{"answer":"The method that makes a type implement error","conceptTag":"errors.custom","id":"review.lesson.errors.custom-type","prompt":"Error() string","promptIsCode":true,"requiredLessonID":"errors.custom-type"},{"answer":"Return an error value rather than panic","conceptTag":"errors.panic","id":"review.lesson.errors.panic","prompt":"An expected input failure","promptIsCode":false,"requiredLessonID":"errors.panic"},{"answer":"Can stop a panic in the same goroutine","conceptTag":"errors.panic","id":"review.lesson.errors.recover","prompt":"recover() in a deferred call","promptIsCode":true,"requiredLessonID":"errors.recover"},{"answer":"A test function in a file ending in _test.go","conceptTag":"stdlib.testing","id":"review.lesson.modules.tests","prompt":"func TestX(t *testing.T)","promptIsCode":true,"requiredLessonID":"modules.tests"},{"answer":"Avoid repeating the package name in exported names","conceptTag":"modules.import-path","id":"review.lesson.modules.naming","prompt":"http.Server, not http.HTTPServer","promptIsCode":false,"requiredLessonID":"modules.naming"},{"answer":"Imported packages initialize before their importers","conceptTag":"packages.init","id":"review.lesson.modules.init","prompt":"Package initialization","promptIsCode":false,"requiredLessonID":"modules.init"},{"answer":"Waits for all work counted by the WaitGroup","conceptTag":"concurrency.waitgroup","id":"review.lesson.concurrency.worker-pool","prompt":"wg.Wait()","promptIsCode":true,"requiredLessonID":"concurrency.worker-pool"},{"answer":"Runs f at most once for that Once instance","conceptTag":"concurrency.once","id":"review.lesson.concurrency.once","prompt":"once.Do(f)","promptIsCode":true,"requiredLessonID":"concurrency.once"},{"answer":"Receives until ch is closed and its buffer is drained","conceptTag":"concurrency.range-channel","id":"review.lesson.concurrency.range-and-close","prompt":"for v := range ch","promptIsCode":true,"requiredLessonID":"concurrency.range-and-close"},{"answer":"Takes default immediately if no case can proceed","conceptTag":"concurrency.select-default","id":"review.lesson.concurrency.select-default","prompt":"select with default","promptIsCode":false,"requiredLessonID":"concurrency.select-default"},{"answer":"Read returns a byte count and an error","conceptTag":"stdlib.io","id":"review.lesson.stdlib.io","prompt":"io.Reader.Read","promptIsCode":true,"requiredLessonID":"stdlib.io"},{"answer":"A struct tag controlling a JSON field's encoding","conceptTag":"stdlib.json","id":"review.lesson.stdlib.json","prompt":"json:\"name,omitempty\"","promptIsCode":true,"requiredLessonID":"stdlib.json"},{"answer":"An integer count of nanoseconds","conceptTag":"stdlib.time","id":"review.lesson.stdlib.time","prompt":"time.Duration","promptIsCode":true,"requiredLessonID":"stdlib.time"},{"answer":"Uses a comparator to order slice elements","conceptTag":"stdlib.sort","id":"review.lesson.stdlib.sort","prompt":"slices.SortFunc","promptIsCode":true,"requiredLessonID":"stdlib.sort"},{"answer":"Releases resources for the derived context","conceptTag":"context.cancel","id":"review.lesson.stdlib.context","prompt":"defer cancel()","promptIsCode":true,"requiredLessonID":"stdlib.context"},{"answer":"Not allowed; use var or const at package scope","conceptTag":"vars.short-declaration","id":"review.core.short-scope","prompt":"Package-level :=","promptIsCode":false,"requiredLessonID":"core.short-declaration"},{"answer":"Assigns to an existing variable; no name is declared","conceptTag":"vars.short-declaration","id":"review.core.assignment","prompt":"x = 3","promptIsCode":true,"requiredLessonID":"core.short-declaration"},{"answer":"The name is not declared or visible in this scope","conceptTag":"packages.undefined","id":"review.diagnostic.undefined","prompt":"undefined: name","promptIsCode":false,"requiredLessonID":"modules.import-path"},{"answer":"Not assignable: int and string are different types","conceptTag":"types.assignment","id":"review.diagnostic.assignment","prompt":"var s string = n // n is int","promptIsCode":true,"requiredLessonID":"core.conversions"},{"answer":"Handle the error before using the returned result","conceptTag":"errors.explicit-check","id":"review.core.error-check","prompt":"if err != nil","promptIsCode":true,"requiredLessonID":"core.multiple-returns"},{"answer":"An import no line in this file refers to","conceptTag":"modules.unused-import","id":"review.core.unused-import","prompt":"imported and not used","promptIsCode":false,"requiredLessonID":"core.unused-is-an-error"},{"answer":"Pass a context as the first parameter, not a field","conceptTag":"context.first-parameter","id":"review.context.parameter","prompt":"func Work(ctx context.Context)","promptIsCode":true,"requiredLessonID":"stdlib.context"}],"reviewRounds":[{"id":"review.core","pairs":[{"answer":"Already 0; nothing is uninitialised","conceptTag":"vars.unused","id":"review.core.zero","prompt":"var n int","promptIsCode":true,"requiredLessonID":"core.zero-values"},{"answer":"Declares, and only inside a function","conceptTag":"vars.short-declaration","id":"review.core.short","prompt":"x := 3","promptIsCode":true,"requiredLessonID":"core.short-declaration"},{"answer":"Two results instead of one exception","conceptTag":"functions.missing-return","id":"review.core.returns","prompt":"v, err := Open()","promptIsCode":true,"requiredLessonID":"core.multiple-returns"},{"answer":"A local you named but never read","conceptTag":"vars.unused","id":"review.core.unused","prompt":"declared and not used","promptIsCode":false,"requiredLessonID":"core.unused-is-an-error"},{"answer":"Untyped until a use gives it a type","conceptTag":"types.constants","id":"review.core.const","prompt":"const n = 3","promptIsCode":true,"requiredLessonID":"core.constants"}],"subtitle":"Names, zeros and what the compiler rejects","title":"Go core","unitID":"core"},{"id":"review.collections","pairs":[{"answer":"len is readable; cap is room to grow","conceptTag":"slices.capacity","id":"review.col.len","prompt":"len(s) vs cap(s)","promptIsCode":true,"requiredLessonID":"collections.length-capacity"},{"answer":"Shares a's array until one of them grows","conceptTag":"slices.aliasing","id":"review.col.alias","prompt":"b := a[1:3]","promptIsCode":true,"requiredLessonID":"collections.append-aliasing"},{"answer":"The zero value, not an error or a panic","conceptTag":"maps.zero-value","id":"review.col.map","prompt":"m[\"missing\"]","promptIsCode":true,"requiredLessonID":"collections.map-zero-value"},{"answer":"r is a rune; i counts bytes","conceptTag":"strings.runes","id":"review.col.runes","prompt":"for i, r := range s","promptIsCode":true,"requiredLessonID":"collections.runes-not-bytes"},{"answer":"yield stops the loop when it returns false","conceptTag":"range-over-func","id":"review.col.iter","prompt":"range over a function","promptIsCode":false,"requiredLessonID":"collections.iterators"}],"subtitle":"What the header actually holds","title":"Slices, maps, strings","unitID":"collections"},{"id":"review.types","pairs":[{"answer":"A keyed struct literal; other fields stay zero","conceptTag":"types.struct-literal","id":"review.types.struct","prompt":"Person{Name: \"Ada\"}","promptIsCode":true,"requiredLessonID":"structs.literals"},{"answer":"Only *Counter has Add, never Counter","conceptTag":"interfaces.method-set","id":"review.types.method","prompt":"func (c *Counter) Add()","promptIsCode":true,"requiredLessonID":"structs.methods"},{"answer":"A pointer is for changing, not for speed","conceptTag":"types.pointer","id":"review.types.ptr","prompt":"p := &value","promptIsCode":true,"requiredLessonID":"structs.pointers"},{"answer":"The consumer names the methods it needs","conceptTag":"interfaces.size","id":"review.types.iface","prompt":"type Reader interface","promptIsCode":true,"requiredLessonID":"interfaces.implicit"},{"answer":"A nil pointer inside a non-nil interface","conceptTag":"interfaces.nil","id":"review.types.nil","prompt":"err != nil, but err is nil","promptIsCode":false,"requiredLessonID":"interfaces.nil"}],"subtitle":"Who owns the data, who names the methods","title":"Types and interfaces","unitID":"structs"},{"id":"review.errors","pairs":[{"answer":"Adds context; the cause stays reachable","conceptTag":"errors.wrapping","id":"review.err.wrap","prompt":"fmt.Errorf(\"...: %w\", err)","promptIsCode":true,"requiredLessonID":"errors.wrapping"},{"answer":"Compares a sentinel through wrapping","conceptTag":"errors.sentinel","id":"review.err.is","prompt":"errors.Is(err, io.EOF)","promptIsCode":true,"requiredLessonID":"errors.is-and-as"},{"answer":"Runs last-in first-out, every return","conceptTag":"errors.defer","id":"review.err.defer","prompt":"defer f.Close()","promptIsCode":true,"requiredLessonID":"errors.defer"},{"answer":"Module path plus the directory","conceptTag":"modules.import-path","id":"review.mod.path","prompt":"import \"mod/pkg\"","promptIsCode":true,"requiredLessonID":"modules.import-path"},{"answer":"A capital letter is the access modifier","conceptTag":"interfaces.size","id":"review.mod.export","prompt":"func Parse()","promptIsCode":true,"requiredLessonID":"modules.exported-by-case"}],"subtitle":"Values, wrapping, and what a capital letter means","title":"Errors and packages","unitID":"errors"},{"id":"review.concurrency","pairs":[{"answer":"A meeting: send waits for a receiver","conceptTag":"concurrency.deadlock","id":"review.conc.unbuf","prompt":"make(chan int)","promptIsCode":true,"requiredLessonID":"concurrency.unbuffered-rendezvous"},{"answer":"Starts a goroutine and returns nothing","conceptTag":"concurrency.goroutine-leak","id":"review.conc.go","prompt":"go work()","promptIsCode":true,"requiredLessonID":"concurrency.no-handle"},{"answer":"The sender's job, and only ever once","conceptTag":"concurrency.channel-close","id":"review.conc.close","prompt":"close(ch)","promptIsCode":true,"requiredLessonID":"concurrency.channel-close"},{"answer":"Waits on several cases; context says stop","conceptTag":"concurrency.select","id":"review.conc.select","prompt":"select { ... }","promptIsCode":true,"requiredLessonID":"concurrency.select-context"},{"answer":"A mutex is for state you keep","conceptTag":"concurrency.mutex","id":"review.conc.mutex","prompt":"mu.Lock(); defer Unlock","promptIsCode":true,"requiredLessonID":"concurrency.mutex"}],"subtitle":"What blocks, who closes, and what a lock is for","title":"Concurrency","unitID":"concurrency"},{"id":"review.tour","pairs":[{"answer":"Sends the named results as they stand","conceptTag":"functions.named-results","id":"review.tour.named","prompt":"return  // naked","promptIsCode":true,"requiredLessonID":"core.named-results"},{"answer":"make initializes; new returns a pointer","conceptTag":"builtin.make-new","id":"review.tour.make","prompt":"make vs new","promptIsCode":false,"requiredLessonID":"collections.make-and-new"},{"answer":"The length is part of the type","conceptTag":"types.array","id":"review.tour.array","prompt":"[4]int vs [3]int","promptIsCode":true,"requiredLessonID":"collections.arrays"},{"answer":"String(); fmt looks for it","conceptTag":"fmt.stringer","id":"review.tour.stringer","prompt":"fmt.Stringer","promptIsCode":true,"requiredLessonID":"interfaces.stringer"},{"answer":"interface{} with zero methods","conceptTag":"interfaces.empty","id":"review.tour.any","prompt":"any","promptIsCode":true,"requiredLessonID":"interfaces.empty"}],"subtitle":"Named results, make, arrays, Stringer, any","title":"From A Tour of Go","unitID":"core"},{"id":"review.stdlib","pairs":[{"answer":"ServeHTTP, one method","conceptTag":"stdlib.http","id":"review.std.http","prompt":"http.Handler","promptIsCode":true,"requiredLessonID":"stdlib.http"},{"answer":"Text to int, plus an error","conceptTag":"stdlib.strconv","id":"review.std.atoi","prompt":"strconv.Atoi","promptIsCode":true,"requiredLessonID":"stdlib.strconv"},{"answer":"ColorModel, Bounds and At","conceptTag":"stdlib.image","id":"review.std.image","prompt":"image.Image","promptIsCode":true,"requiredLessonID":"stdlib.image"},{"answer":"A mailbox; send waits when full","conceptTag":"concurrency.buffered","id":"review.std.buf","prompt":"make(chan T, n)","promptIsCode":true,"requiredLessonID":"concurrency.buffered"},{"answer":"Send-only; close lives here","conceptTag":"concurrency.channel-direction","id":"review.std.dir","prompt":"chan<- int","promptIsCode":true,"requiredLessonID":"concurrency.direction"}],"subtitle":"Handler, Atoi, Image, buffers, direction","title":"Stdlib and channels","unitID":"stdlib"}]},"readings":[{"afterLessonID":"core.short-declaration","conceptTag":"vars.short-declaration","hint":"Track each name together with the block that declares it.","id":"core.declarations-walkthrough","introduction":"A useful way to read Go is to ask three questions at each assignment: which block owns this name, what type does it have, and is a new variable being created? The spelling of a name alone does not answer any of them.","nuance":"A nested declaration and an assignment have different effects even when the name is spelled identically.","objective":"Follow values through a short declaration, an assignment and a shadowed name without running the program.","question":"Which statement is correct about nested :=?","references":["https://go.dev/ref/spec#Short_variable_declarations"],"reviewAnswer":"May hide an outer variable with a new local name","reviewPrompt":"Nested :=","sections":[{"body":"Start with a local variable. Its type comes from the expression on the right. An ordinary assignment updates that same variable; it does not create another binding. Read the two lines as a small state table: first count is 2, then count is 5.","code":"count := 2\ncount = count + 3\nfmt.Println(count) // 5","language":"go","title":"Trace the original variable","walkthrough":"The right side is evaluated before the assignment. The old count contributes 2, the expression becomes 5, and only then is count updated. This is useful when stepping through a counter, an index or a retry budget."},{"body":"An if body is a new lexical block. A short declaration there may hide an outer variable. This can be intentional for a temporary result, but it becomes confusing when the outer result was supposed to change.","code":"name := \"outside\"\nif ok {\n    name := \"inside\"\n    fmt.Println(name) // inside\n}\nfmt.Println(name) // outside","language":"go","title":"A nested block owns a different name","walkthrough":"The inner name stops being accessible at the closing brace. Replacing its := with = would instead update the outer string. The difference is scope, not a special rule about if."},{"body":"In a multi-name short declaration, at least one non-blank name must be new in the same block. Existing names in that block keep their declared types. Before changing := to =, find every declaration and branch exit; an inner err may be a deliberate short-lived error, or it may hide the value returned later.","title":"Use the rule while reviewing real code"}],"takeaway":"Read the block before the operator. Prefer a short temporary scope when it clarifies ownership; use assignment when an existing result must change.","title":"Read a declaration one scope at a time","unitID":"core","wrongAnswers":["It is automatically overwritten when the block ends","It becomes a pointer to the inner variable"]},{"beforeLessonID":"core.multiple-returns","conceptTag":"errors.explicit-check","hint":"Walk through one invalid input and one valid input before reading the success return.","id":"core.error-path-walkthrough","introduction":"An error result is part of a function contract. The caller needs to know whether a value is valid when err is non-nil, who should add context, and which layer decides what the user sees. A short early return makes that contract visible.","nuance":"An error does not universally invalidate every returned value; the called API defines that contract.","objective":"Trace a result and error through a complete boundary, including wrapping and partial results.","question":"Which statement is correct about a result with an error?","references":["https://go.dev/blog/error-handling-and-go","https://pkg.go.dev/io#Reader"],"reviewAnswer":"Use partial data only when its API contract permits it","reviewPrompt":"A result with an error","sections":[{"body":"This function promises a useful positive integer only when its error is nil. Invalid syntax and a non-positive number are different failures. In each failure branch, return immediately; the normal result appears once at the bottom.","code":"func positive(raw string) (int, error) {\n    n, err := strconv.Atoi(raw)\n    if err != nil {\n        return 0, fmt.Errorf(\"parse count: %w\", err)\n    }\n    if n <= 0 {\n        return 0, errors.New(\"count must be positive\")\n    }\n    return n, nil\n}","language":"go","title":"Trace both returns","walkthrough":"For \"abc\", Atoi fails and the first branch exits. For \"0\", parsing succeeds and validation fails. For \"8\", neither error branch runs and the caller receives 8, nil. No exception handler is needed to follow those paths."},{"body":"The helper adds operation context without choosing an HTTP status or printing to a console. A CLI handler or HTTP adapter can decide how to report the error. Avoid logging the same error at every layer; repeated messages obscure a single failure.","title":"Handle it at the boundary"},{"body":"Some APIs deliberately return useful data with an error. io.Reader is a notable example: process the bytes returned before deciding what the error means. Do not generalize the early-return pattern into discarding all non-zero results. Read the particular API contract and distinguish expected absence, invalid input and infrastructure failure.","title":"Partial results need a documented contract"}],"takeaway":"Follow each return as a pair. Handle errors deliberately, preserve a useful cause with wrapping, and use partial values only when the API promises them.","title":"Read the failure path before the happy path","unitID":"core","wrongAnswers":["Whenever the value is not its zero value","Only after converting the error to a string"]},{"beforeLessonID":"collections.length-capacity","conceptTag":"slices.aliasing","hint":"Draw the array once and point both slice windows at it.","id":"collections.slice-walkthrough","introduction":"A slice describes a region of an array. Copying a slice value copies its descriptor, not all the elements. Two descriptors may therefore refer to the same elements while having different lengths and capacities.","nuance":"Capacity clipping controls append reuse; it does not isolate writes to elements already in the slice.","objective":"Predict a subslice, an element write and append by tracking the backing array.","question":"Which statement is correct about copying a slice header?","references":["https://go.dev/blog/slices-intro","https://pkg.go.dev/slices#Clone"],"reviewAnswer":"Can still share the original backing array","reviewPrompt":"Copying a slice header","sections":[{"body":"Treat the array as three numbered cells and each slice as a window over those cells. b begins at the second cell of a. Updating b[0] changes that cell; a observes it because it still refers to the same array.","code":"a := []int{10, 20, 30}\nb := a[1:3]\nb[0] = 99\nfmt.Println(a) // [10 99 30]\nfmt.Println(b) // [99 30]","language":"go","title":"Draw the shared storage","walkthrough":"No goroutines are involved here. This is aliasing in a single execution flow. It matters for helper functions that appear to return a fresh view but actually let their callers change the original data."},{"body":"Append may reuse storage when capacity is available, or allocate storage when it is not. Assign its result because the returned descriptor can change. A full slice expression can restrict capacity, preventing an append through that view from using the hidden tail; existing element writes still share storage.","code":"a := []int{10, 20, 30}\nb := a[:1:1] // len 1, cap 1\nb = append(b, 40)\nb[0] = 7\nfmt.Println(a) // [10 20 30]","language":"go","title":"Capacity affects append, not ownership","walkthrough":"This append must grow beyond b's capacity. Do not depend on a particular capacity growth factor; the language does not promise one."},{"body":"Use slices.Clone for an independent shallow copy of the elements. For slices of pointers or nested slices, the pointed-to objects remain shared. Decide whether you need a view, a shallow clone, or a domain-specific deep copy. Write that decision into the function contract instead of leaving callers to guess.","title":"Choose a copy at the ownership boundary"}],"takeaway":"Track array identity as well as len and cap. A different slice value can still expose the same mutable storage.","title":"A slice is a window, not a copied array","unitID":"collections","wrongAnswers":["All elements into a new independent array","The original array and every object reachable from it"]},{"afterLessonID":"collections.append-aliasing","conceptTag":"concurrency.mutex","hint":"Separate the slice header from its elements and identify every writer.","id":"collections.concurrent-slices","introduction":"A goroutine does not make its arguments private. If two workers share a slice, you must reason about the slice descriptor and the array it refers to. Making extra goroutines can expose an ownership mistake that a sequential example concealed.","nuance":"Independent slots are safe only with fixed ownership and synchronization before the final read.","objective":"Separate shared headers, shared elements and safe collection of concurrent results.","question":"Which statement is correct about concurrent append?","references":["https://go.dev/ref/mem","https://go.dev/doc/articles/race_detector.html"],"reviewAnswer":"Needs one owner or synchronization, even with capacity","reviewPrompt":"Concurrent append","sections":[{"body":"Concurrent append to one shared slice variable reads and writes the same descriptor and may write the same backing storage. Even if capacity is large enough, append still changes the shared length. Reserving capacity is a performance choice, not synchronization.","code":"// Unsafe: both goroutines update the same slice.\nvar results []int\ngo func() { results = append(results, 1) }()\ngo func() { results = append(results, 2) }()","language":"go","title":"Why append needs coordination","walkthrough":"The outcome is not a reliable permutation of [1 2]. This is a deliberate counterexample, not code to copy. A passing test without the race detector does not establish safety."},{"body":"A pre-sized slice permits independent element writes when each worker owns a different index, no worker changes the descriptor, and the reader waits for every writer. Elements that themselves contain shared pointers need their own ownership rules.","code":"results := make([]int, len(inputs))\nvar wg sync.WaitGroup\nfor i, value := range inputs {\n    wg.Add(1)\n    go func(i, value int) {\n        defer wg.Done()\n        results[i] = value * 2\n    }(i, value)\n}\nwg.Wait() // Read results only after the writers finish.","language":"go","title":"Give each worker a separate slot","walkthrough":"Index i is assigned to exactly one goroutine. WaitGroup orders the final read after the completed writes. For very large inputs, combine this ownership pattern with a bounded worker pool rather than starting a goroutine per item."},{"body":"If each job returns an unknown number of values, let workers send results to one owner that appends, or protect every access with the same mutex. A channel transfers values; it does not deep-copy a slice payload. The sender must stop mutating transferred storage or clone it first. Run race-enabled tests on a supported desktop toolchain; the app does not offer a native race detector.","title":"Use a single collector for variable-length output"}],"takeaway":"Concurrency safety comes from ownership and synchronization, not spare capacity. Distinct indexes plus a final join differ from concurrent append.","title":"Shared slices and concurrent append","unitID":"collections","wrongAnswers":["Needs synchronization only when append allocates","Is always safe when the element type is int"]},{"afterLessonID":"collections.bounds","conceptTag":"runtime.allocation","hint":"Look for a small cached value that still points into a large input.","id":"collections.retained-buffers","introduction":"Visible length is not retained memory size. A small view can keep an entire allocation reachable. This is often noticed when a parser, cache or queue stores a few bytes from each large input and memory grows far beyond the stored lengths.","nuance":"Reducing a slice capacity does not copy storage or shorten the backing array lifetime.","objective":"Recognize retained backing arrays and detach small long-lived results deliberately.","question":"Which statement is correct about a long-lived subslice?","references":["https://go.dev/blog/slices-intro","https://pkg.go.dev/bytes#Clone","https://go.dev/doc/diagnostics"],"reviewAnswer":"Can retain a much larger backing allocation","reviewPrompt":"A long-lived subslice","sections":[{"body":"The function returns only sixteen bytes, but the result still points into the large allocation. As long as that backing array remains reachable, garbage collection cannot reclaim the array just because most of its bytes are outside the returned view.","code":"func prefix() []byte {\n    data := make([]byte, 8<<20)\n    // A real program would read data here.\n    return data[:16]\n}","language":"go","title":"Follow the reference that survives","walkthrough":"The 8 MiB allocation is an illustrative size, not a threshold in Go. The problem is the lifetime mismatch: a short prefix outlives the large buffer it views."},{"body":"Copy a small result when it needs an independent lifetime. The copy costs time and an allocation, so use it at a boundary such as inserting into a long-lived cache, not indiscriminately inside every short-lived operation.","code":"func detachedPrefix(data []byte) []byte {\n    n := min(16, len(data))\n    return bytes.Clone(data[:n])\n}","language":"go","title":"Detach only what must outlive the input","walkthrough":"Clipping capacity with data[:n:n] alone would not detach the original array. Setting one local variable to nil also does not help while another live view still refers to the allocation."},{"body":"Distinguish bytes allocated over time from bytes still live. A temporary copy can increase allocation traffic while reducing retained memory. Inspect heap profiles in the real service, reproduce with representative payloads, and compare before and after. For slices of pointers, discarded elements can also retain pointed-to objects; use appropriate clearing or slices helpers when shrinking reusable storage.","title":"Measure retention rather than guessing"}],"takeaway":"Optimize lifetimes, not just lengths. A small copy can release a much larger backing array once all other references are gone.","title":"A tiny slice can keep a large buffer alive","unitID":"collections","wrongAnswers":["Always releases the unused backing bytes immediately","Owns an independent copy of only its visible elements"]},{"afterLessonID":"concurrency.worker-pool","conceptTag":"services.capacity","hint":"Find the slowest resource and the queue in front of it.","id":"concurrency.bounded-work","introduction":"Concurrency is how work overlaps. Capacity is how much useful work the system can sustain. A thousand waiting goroutines do not give Redis a thousand extra cores or increase a database connection budget. They do consume memory, queue time and cancellation bookkeeping.","nuance":"An unbounded population of goroutines waiting for a semaphore is still an unbounded queue.","objective":"Bound active workers and queued work according to the resource that actually limits throughput.","question":"Which statement is correct about a bounded worker pool?","references":["https://go.dev/blog/pipelines","https://pkg.go.dev/golang.org/x/sync/errgroup#Group.SetLimit"],"reviewAnswer":"Limits concurrent jobs, not requests per second","reviewPrompt":"A bounded worker pool","sections":[{"body":"Suppose one downstream operation takes about 20 ms at the target load. Twenty concurrent operations can support roughly 1,000 operations per second in that simplified steady-state example. Real latency distributions, payload size and server limits change the result. Treat it as a sizing hypothesis, then measure tail latency and saturation.","title":"Start with a budget"},{"body":"A fixed worker count bounds active calls. A bounded jobs channel also bounds queued work. A context-aware producer stops waiting when the request is no longer useful. This fragment shows the admission point; workers, cancellation and channel ownership must all belong to the same enclosing operation.","code":"jobs := make(chan Job, 32)\n// Start a fixed number of workers elsewhere.\nselect {\ncase jobs <- job:\n    // Accepted into the bounded queue.\ncase <-ctx.Done():\n    return ctx.Err()\n}","language":"go","title":"Apply admission control before creating more work","walkthrough":"Do not launch a new goroutine for every rejected or blocked enqueue: that merely moves an unbounded queue from the channel into goroutine stacks."},{"body":"For request/response traffic, reject work that cannot meet its deadline or wait only within a bounded budget. For background work, use a durable queue if losing work is unacceptable. A worker pool limits concurrency, not requests per second; add rate limiting when the downstream contract is a rate. Track active calls, queue depth, queue age, errors and latency together.","title":"Pick a deliberate overload response"}],"takeaway":"Bound workers, waiting work and waiting time. Size those limits from downstream behavior, then verify under load.","title":"More goroutines are not more capacity","unitID":"concurrency","wrongAnswers":["It increases the dependency's physical capacity automatically","It removes all queueing and timeout costs"]},{"afterLessonID":"concurrency.no-handle","conceptTag":"concurrency.goroutine-leak","hint":"Identify the stop signal and the acknowledgement as two separate events.","id":"concurrency.cancel-and-join","introduction":"Starting a goroutine creates an obligation: identify who asks it to stop and who observes that it has stopped. Canceling a context closes a signal; it does not terminate arbitrary Go code. Every blocking point must cooperate or have another bounded exit.","nuance":"A context only helps at code paths and APIs that observe it; cancellation alone does not join workers.","objective":"Design a worker so it can stop waiting and its owner can wait for it to finish.","question":"Which statement is correct about cancellation and joining?","references":["https://go.dev/blog/pipelines","https://pkg.go.dev/context"],"reviewAnswer":"Request a stop, then observe the worker finishing","reviewPrompt":"Cancellation and joining","sections":[{"body":"A producer may outlive its consumer. If the consumer returns early, an unconditional send can wait forever and keep its goroutine and reachable objects alive. Select between sending and cancellation.","code":"func send(ctx context.Context, out chan<- Item, item Item) error {\n    select {\n    case out <- item:\n        return nil\n    case <-ctx.Done():\n        return ctx.Err()\n    }\n}","language":"go","title":"A blocked send needs an escape","walkthrough":"If the send and cancellation are both ready, select may choose either. Design the protocol to tolerate that race in intent; cancellation does not mean no operation can ever finish afterwards."},{"body":"A done channel acknowledges exit. The owner cancels, then waits. The worker must observe ctx, including inside downstream operations, or this wait can still block. Production shutdown also needs an overall timeout and a clear policy when a dependency refuses to return.","code":"ctx, cancel := context.WithCancel(parent)\ndone := make(chan struct{})\ngo func() {\n    defer close(done)\n    runWorker(ctx) // Must cooperate with cancellation.\n}()\n// Later, in the owner:\ncancel()\n<-done","language":"go","title":"Wait for the owned goroutine","walkthrough":"The worker closes done because it owns the completion signal. Do not close a work channel from an unrelated receiver while senders may still use it."},{"body":"For every worker, list start, inputs, outputs, stop signal and join point. Include error paths, not only success. Context does not interrupt a mutex lock or CPU loop automatically; choose primitives and loop checkpoints accordingly. A finalizer or the garbage collector is not a goroutine cleanup strategy.","title":"Use a lifecycle checklist"}],"takeaway":"Cancellation communicates intent. A join or completion acknowledgement establishes that the owned work has actually stopped.","title":"Cancellation is a request; joining proves exit","unitID":"concurrency","wrongAnswers":["Cancellation proves every worker has already exited","Cancellation forcibly interrupts every blocking primitive"]},{"conceptTag":"runtime.allocation","hint":"Separate the language lifetime guarantee from a particular allocation decision.","id":"runtime.stack-and-heap","introduction":"Lifetime is the semantic question: how long must a value remain usable? Stack and heap placement are implementation choices used to satisfy that requirement. The compiler performs escape analysis; source syntax alone is not a dependable allocation profiler.","nuance":"Pointer syntax does not prove a heap allocation, and a value expression is not a promise of zero allocations.","objective":"Explain why returning a local address is safe and why allocation placement must be measured.","question":"Which statement is correct about escape analysis?","references":["https://go.dev/doc/faq#stack_or_heap","https://go.dev/doc/diagnostics"],"reviewAnswer":"Helps determine stack versus heap storage","reviewPrompt":"Escape analysis","sections":[{"body":"Returning a pointer to a local value is normal Go. The implementation arranges storage so callers do not receive a dangling pointer. Do not import C stack-lifetime rules into this code.","code":"type Counter struct { N int }\nfunc newCounter() *Counter {\n    c := Counter{N: 1}\n    return &c\n}","language":"go","title":"A local address can safely leave a function","walkthrough":"The local spelling c does not disappear in a way that invalidates the returned pointer. Exactly which allocations survive optimization can depend on inlining and the surrounding call sites."},{"body":"A value receiver copies its receiver; a pointer receiver allows shared mutation and may be required by method sets. Neither form is universally faster. Large copies, escaping references, cache locality and synchronization all matter. Start with ownership and API semantics, then inspect a benchmark that represents the actual use.","title":"Pointers are a design decision first"},{"body":"On a desktop Go installation, compiler diagnostics can report escape decisions. Their wording and decisions can change across versions; they are observations, not API guarantees.","code":"go build -gcflags=\"-m=2\" ./...\ngo test -bench=. -benchmem ./...","language":"shell","title":"Inspect the native build, not an assumption","walkthrough":"Use these commands in your development environment. Compare allocations per operation and time after warm-up. The app's WebAssembly sandbox does not reproduce every native service allocation or threading cost."}],"takeaway":"Reason about required lifetime first. Use compiler diagnostics and measurements to learn how the implementation realizes it.","title":"Stacks, escape analysis and object lifetimes","unitID":"runtime","wrongAnswers":["The pointer always expires on the next function call","The caller must manually free the local stack frame"]},{"conceptTag":"runtime.gc","hint":"Follow every remaining reference path, including caches and blocked workers.","id":"runtime.gc-reachability","introduction":"Garbage collection reclaims memory that the runtime determines is no longer reachable. It does not know that an application has lost interest in a cache entry, nor does it close a forgotten network connection on a useful schedule. Ownership still matters.","nuance":"Eligible for collection does not mean the same bytes disappear from process RSS immediately.","objective":"Follow references from roots and distinguish unreachable objects from unwanted live data.","question":"Which statement is correct about a cached reachable object?","references":["https://go.dev/doc/gc-guide","https://pkg.go.dev/runtime"],"reviewAnswer":"Stays live while strong references still reach it","reviewPrompt":"A cached reachable object","sections":[{"body":"Imagine a global cache holding a pointer to an order, which points to a large receipt buffer. As long as a live reference path reaches the buffer, it is not garbage. Removing one local reference is insufficient when the cache still holds another.","code":"type Order struct { Receipt []byte }\nvar cache = map[string]*Order{}\n\nfunc remember(id string, receipt []byte) {\n    cache[id] = &Order{Receipt: receipt}\n}\n// These helpers assume a single owner of cache.\nfunc forget(id string) {\n    delete(cache, id)\n}","language":"go","title":"Think in reference paths","walkthrough":"Delete removes this map entry, not every possible reference to the order. Concurrent access to the map would require synchronization. The example focuses only on the reference graph."},{"body":"An unreachable allocation becomes eligible for reclamation; there is no promise that the operating system immediately receives the same amount of memory. Runtime-managed free space can be reused. RSS, live heap and total allocated bytes answer different questions, so compare like with like when diagnosing growth.","title":"Collection is not immediate destruction"},{"body":"Close files and response bodies, stop owned background workers, and bound caches according to their contracts. A tracing collector can collect unreachable cycles, but it cannot make an indefinitely blocked goroutine release the values it still reaches. Avoid finalizers as normal cleanup: their timing does not establish a reliable resource protocol.","title":"Resources need explicit lifetime management"}],"takeaway":"The GC answers reachability, not business usefulness. Remove unwanted references and close resources explicitly; then measure the correct memory metric.","title":"What the garbage collector can and cannot free","unitID":"runtime","wrongAnswers":["The garbage collector never handles byte slices","Setting any variable to nil disables future collection"]},{"conceptTag":"runtime.gc","hint":"Compare allocation rate, live heap and process memory before choosing a knob.","id":"runtime.gc-budget","introduction":"A service pays for memory in more than one way: live objects occupy space, new allocations create work, and collection uses CPU. Tuning a single GC knob cannot repair an unbounded cache or a queue that retains every request body.","nuance":"The runtime memory limit is soft and cannot substitute for a bounded workload or a measured container budget.","objective":"Distinguish reducing live data from tuning collection frequency and respect a container memory limit.","question":"Which statement is correct about gomemlimit?","references":["https://go.dev/doc/gc-guide","https://pkg.go.dev/runtime/debug#SetMemoryLimit","https://pkg.go.dev/sync#Pool"],"reviewAnswer":"A soft runtime budget, not a process hard cap","reviewPrompt":"GOMEMLIMIT","sections":[{"body":"A high allocation rate with a small live heap suggests churn: many objects become garbage quickly. A growing live heap suggests retained data or a growing workload. Capture representative profiles before changing code; removing one temporary allocation is not helpful if a cache retains gigabytes indefinitely.","title":"Measure two different problems"},{"body":"GOGC influences the heap-growth target and therefore the tradeoff between collection frequency and memory. GOMEMLIMIT is a soft runtime memory limit, not an operating-system hard cap. Native allocations and other process memory can require additional budget. Leave measured headroom under the container limit rather than making the two numbers equal.","code":"# Illustrative native-service configuration, not an iOS setting:\nGOGC=100 GOMEMLIMIT=400MiB ./service","language":"shell","title":"Treat settings as tradeoffs","walkthrough":"The 400 MiB value is an example, not a recommendation for every 512 MiB container. Measure your binary, traffic and non-runtime memory before choosing a value."},{"body":"Avoid retaining whole request graphs in queues, bound cache entries, and reuse buffers only with clear ownership and size limits. Increasing a memory allowance may reduce collection frequency but raises memory use; forcing very frequent GC can waste CPU. A pool is an optimization with lifecycle constraints, not a guarantee that objects will stay cached or that memory use is bounded.","title":"Reduce work before aggressive tuning"}],"takeaway":"First bound live data and measure allocation churn. Then tune collection within an observed process budget and recheck latency under load.","title":"GC cost, allocation rate and memory budgets","unitID":"runtime","wrongAnswers":["A hard cap covering every byte used by the process","A fixed limit on the number of queued requests"]},{"conceptTag":"runtime.scheduler","hint":"Count tasks, execution slots and operating-system threads as different quantities.","id":"runtime.goroutines-and-threads","introduction":"A goroutine is a Go execution task scheduled by the runtime. An OS thread is an operating-system execution resource. The runtime multiplexes tasks onto threads; counting goroutines therefore does not tell you how many cores are doing useful work.","nuance":"A low CPU percentage can coexist with severe overload caused by blocked downstream calls and growing queues.","objective":"Explain concurrency versus parallel execution without assuming a goroutine is an OS thread.","question":"Which statement is correct about gomaxprocs?","references":["https://go.dev/src/runtime/HACKING","https://pkg.go.dev/runtime#GOMAXPROCS"],"reviewAnswer":"Limits parallel Go execution slots, not goroutines","reviewPrompt":"GOMAXPROCS","sections":[{"body":"In runtime terminology G represents a goroutine, M an OS thread, and P the scheduler resources needed to execute ordinary Go code. GOMAXPROCS controls how many Ps execute Go code at once. It is not a limit on total goroutines or a universal limit on all process threads.","title":"Use the G, M, P model carefully"},{"body":"Several CPU-bound tasks need available execution capacity to run in parallel. Waiting network operations can overlap while other work proceeds. Starting ten thousand CPU-heavy goroutines does not create ten thousand cores and may add scheduling overhead. Native defaults can account for runtime and container configuration; inspect the actual service instead of copying a magic setting.","code":"fmt.Println(\"Go execution slots:\", runtime.GOMAXPROCS(0))\nfmt.Println(\"goroutines now:\", runtime.NumGoroutine())","language":"go","title":"CPU work and waiting behave differently","walkthrough":"Passing zero queries the current GOMAXPROCS value. NumGoroutine is a snapshot and includes runtime/application work; it is a diagnostic signal, not a precise request counter."},{"body":"For CPU work, benchmark a bounded pool around the available CPU budget. For I/O work, use downstream concurrency, queue and deadline limits. A service can be overloaded with many waiting tasks even when CPU looks low. The iOS app's WebAssembly execution environment does not demonstrate native OS-thread behavior; these examples describe native Go services.","title":"Choose the right concurrency level"}],"takeaway":"Goroutines express concurrency. The runtime and OS determine parallel execution within available CPU and downstream budgets.","title":"Goroutines, OS threads and GOMAXPROCS","unitID":"runtime","wrongAnswers":["Reserves one physical core for every goroutine","Places a fixed bound on the total number of goroutines"]},{"conceptTag":"runtime.profiling","hint":"Pick the profile that can actually observe the suspected resource.","id":"runtime.profiles-and-leaks","introduction":"A rising memory graph is a symptom. Before changing code, ask whether traffic grew, objects are retained, workers are stuck, or allocation churn became expensive. Different diagnostic tools answer different questions.","nuance":"Profiles need workload context; a large cumulative allocation total does not itself establish a live-memory leak.","objective":"Choose a heap profile, goroutine profile, CPU profile or trace to test a specific hypothesis.","question":"Which statement is correct about a goroutine profile?","references":["https://go.dev/doc/diagnostics","https://pkg.go.dev/runtime/pprof","https://pkg.go.dev/runtime/trace"],"reviewAnswer":"Shows stacks that help locate blocked workers","reviewPrompt":"A goroutine profile","sections":[{"body":"A heap profile helps find retained allocations; allocation profiles emphasize cumulative allocation traffic. A goroutine profile shows where tasks wait. CPU sampling identifies code consuming CPU, while an execution trace exposes scheduling and blocking relationships. Compare the same workload and interval rather than comparing unrelated snapshots.","title":"Choose the observation"},{"body":"For a native local program, a goroutine profile can be written to a file without opening an HTTP diagnostics server. Handle the file error and close the file. Profiles can include operational details, so store and share them deliberately.","code":"f, err := os.Create(\"goroutines.txt\")\nif err != nil {\n    return err\n}\ndefer f.Close()\nif err := pprof.Lookup(\"goroutine\").WriteTo(f, 1); err != nil {\n    return err\n}","language":"go","title":"Write a bounded diagnostic capture","walkthrough":"This fragment belongs inside an error-returning diagnostic function and imports os and runtime/pprof. Capture once at the relevant time; do not create an unbounded stream of profile files."},{"body":"If goroutine count grows after requests finish, compare stacks and identify the owner of the repeated wait. If heap grows with cache keys, inspect eviction and reference lifetimes. Change one thing and repeat the workload. A single stable run does not prove absence of races or leaks, and profiling overhead itself should be considered.","title":"Turn a suspicion into a comparison"}],"takeaway":"Name the hypothesis, choose a tool that can observe it, and compare equivalent workloads before and after the change.","title":"Find a leak by following evidence","unitID":"runtime","wrongAnswers":["Only the application binary size","Only the total number of source files"]},{"conceptTag":"stdlib.http","hint":"Follow the request from validation to the final response, including cancellation.","id":"services.http-lifecycle","introduction":"A Go web service is more than a route callback. Every request consumes a connection, parsing work, application time and possibly downstream capacity. Give those resources explicit lifetimes. This lesson describes native server code; guest Go programs in the app cannot open network sockets.","nuance":"Connection-phase timeouts and a business operation deadline protect different parts of a request.","objective":"Separate request parsing, domain work, downstream deadlines and response writing.","question":"Which statement is correct about an http adapter?","references":["https://pkg.go.dev/net/http#Server","https://pkg.go.dev/net/http/httptest"],"reviewAnswer":"Translates requests and responses around a use case","reviewPrompt":"An HTTP adapter","sections":[{"body":"A handler translates a protocol into an application operation: validate input, call a service with the request context, then map the result to a response. Domain logic should not need a ResponseWriter. If the client leaves, the request context can notify cooperative downstream work.","title":"Keep the boundary small"},{"body":"This is a native-server configuration fragment. Header and idle timeouts address specific connection phases; they are not a complete business-operation deadline. WriteTimeout must fit the response type, especially streaming, rather than being copied blindly.","code":"srv := &http.Server{\n    Addr:              \":8080\",\n    Handler:           handler,\n    ReadHeaderTimeout: 5 * time.Second,\n    IdleTimeout:       60 * time.Second,\n}\n// Start srv and arrange graceful shutdown in the owning process.","language":"go","title":"Configure a server rather than only a callback","walkthrough":"The values are illustrative. Add request-body limits, operation-specific deadlines and response policies based on the API. A timeout does not undo an operation the remote service already committed."},{"body":"HTTP APIs fit request/response interactions and interoperability. A batch program or local library may need no server at all. Test handlers with httptest and in-memory requests before deployment. In-memory handler tests check application behavior; they do not prove production TLS, socket, proxy or load-balancer configuration.","title":"Choose HTTP when it matches the problem"}],"takeaway":"A handler is an adapter with explicit resource limits. Pass context into the application and test protocol behavior without requiring a running network service.","title":"An HTTP request has a lifecycle and a budget","unitID":"services","wrongAnswers":["Owning every domain rule and database implementation","Guaranteeing a remote operation is undone after timeout"]},{"conceptTag":"services.gin","hint":"Read the path prefix, route pattern, parameter and response in that order.","id":"services.gin-routing","introduction":"Gin supplies routing, middleware and request/response helpers on top of net/http. It is useful when those conventions reduce repeated adapter code. It does not supply your domain model, persistence policy or downstream capacity, and a small API can also use the standard library.","nuance":"Gin is optional tooling around HTTP; it does not make an application architecture or network policy for you.","objective":"Read route groups, path parameters and injected dependencies in a small Gin API.","question":"Which statement is correct about a gin route group?","references":["https://gin-gonic.com/en/docs/","https://github.com/gin-gonic/gin/blob/master/docs/doc.md"],"reviewAnswer":"Shares a URL prefix and middleware between routes","reviewPrompt":"A Gin route group","sections":[{"body":"New creates an engine without the default middleware set. The group applies a common path prefix. A named segment is read from the Gin context, then handed to a service. This is an illustrative fragment: store and its result/error contract are application dependencies.","code":"r := gin.New()\nr.Use(gin.Logger(), gin.Recovery())\napi := r.Group(\"/v1\")\napi.GET(\"/items/:id\", func(c *gin.Context) {\n    id := c.Param(\"id\")\n    item, err := store.Find(c.Request.Context(), id)\n    // ErrNotFound is the application's documented sentinel.\n    if errors.Is(err, ErrNotFound) {\n        c.JSON(http.StatusNotFound, gin.H{\"error\": \"item unavailable\"})\n        return\n    }\n    if err != nil {\n        c.JSON(http.StatusServiceUnavailable, gin.H{\"error\": \"service unavailable\"})\n        return\n    }\n    c.JSON(http.StatusOK, item)\n})","language":"go","title":"Read the route from left to right","walkthrough":"The application contract supplies ErrNotFound. Only that classification becomes 404; other failures are not disguised as a missing record. This fragment uses a generic 503 for dependency failure. A complete adapter should distinguish invalid input, internal faults, deadline and cancellation, use the authenticated scope in the lookup and avoid leaking internal error text."},{"body":"Construct a handler with the interface it needs, then register methods on the engine. That makes a fake store available to tests and avoids hiding process configuration in globals. Keep route names and response shapes stable as an external contract.","title":"Inject the dependency, not a global registry"},{"body":"A Gin engine implements http.Handler, so httptest can send an in-memory request through the router and middleware. Assert status, headers and body, including errors. The app includes local-preview patterns, but these reading examples are not a promise that every Gin version or native networking feature runs in its sandbox.","title":"Test routing without starting a server"}],"takeaway":"Use Gin to express the HTTP adapter. Keep application behavior behind explicit dependencies and test the adapter through its Handler interface.","title":"Gin routes are adapters, not the whole application","unitID":"services","wrongAnswers":["It creates a separate operating-system process for every route","It automatically implements the database layer"]},{"conceptTag":"services.gin","hint":"Find the point where input first becomes allowed to cause a side effect.","id":"services.gin-validation","introduction":"Decoded JSON is not yet trusted application input. A field can have the right Go type and still violate a business rule. Bound the body, handle decoding failure, then apply domain validation before writing to storage or calling another service.","nuance":"Required fields and authorization are different checks; valid JSON can still represent an invalid operation.","objective":"Follow JSON binding, size limits, validation and a safe error response.","question":"Which statement is correct about successful json binding?","references":["https://github.com/gin-gonic/gin/blob/master/docs/doc.md","https://pkg.go.dev/net/http#MaxBytesReader"],"reviewAnswer":"Does not prove authorization or every business rule","reviewPrompt":"Successful JSON binding","sections":[{"body":"This adapter accepts a JSON object with a non-empty name. ShouldBindJSON lets the handler choose its error response instead of relying on an automatically written status. The body cap is a policy example and should match the endpoint.","code":"type CreateItem struct {\n    Name string `json:\"name\" binding:\"required,max=80\"`\n}\nfunc create(c *gin.Context) {\n    c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10)\n    var input CreateItem\n    if err := c.ShouldBindJSON(&input); err != nil {\n        c.JSON(http.StatusBadRequest, gin.H{\"error\": \"invalid request\"})\n        return\n    }\n    // Normalize and validate domain rules before persisting input.\n}","language":"go","title":"Separate decoding from application rules","walkthrough":"The generic error avoids echoing an arbitrary decoder message. A production API can map an over-limit body to 413 and expose structured, documented field errors. Decide whether unknown JSON fields should be rejected and configure that policy deliberately."},{"body":"A valid item ID does not prove the requester may access that item. Authenticate the caller, check authorization at the relevant boundary, and keep secrets out of logs and responses. Binding tags check specified shapes; business invariants may require several fields and current state.","title":"Validation does not provide authorization"},{"body":"Cover missing fields, wrong types, malformed and oversized input, duplicate requests and unexpected fields according to the chosen policy. Specify whether optional zero values differ from missing values. If accepting a command has an external effect, consider an idempotency contract rather than assuming retries are harmless.","title":"Test the cases users actually send"}],"takeaway":"Decode, validate shape, enforce business rules and authorization, then perform side effects. Each step has a different responsibility.","title":"Validate a request before doing side effects","unitID":"services","wrongAnswers":["The user is authorized to access every referenced record","The request is safe to retry after any side effect"]},{"conceptTag":"services.redis","hint":"Identify the client pool, the queue and the server as separate limits.","id":"services.redis-capacity","introduction":"Redis can be overwhelmed by too much work, large payloads, expensive commands or many clients competing for the same resources. Making every slice element a goroutine only moves pressure downstream. Treat the server, the network and the client pool as separate budgets.","nuance":"A cache outage can become a database outage if fallback traffic has no admission control.","objective":"Distinguish client pool limits, request deadlines, rate limits and bounded command batches.","question":"Which statement is correct about a redis connection pool?","references":["https://redis.io/docs/latest/develop/clients/go/produsage/","https://redis.io/docs/latest/develop/using-commands/pipelining/"],"reviewAnswer":"Reuses connections; it is not a request-rate limit","reviewPrompt":"A Redis connection pool","sections":[{"body":"A shared client normally reuses connections. Creating a new client for each request defeats that reuse. A connection-pool setting is not automatically a global rate limiter, and waiting for a connection still consumes request time. Exact option semantics depend on the client version; read its production documentation.","title":"Understand what a client pool limits"},{"body":"This native Go fragment assumes a configured shared go-redis client. Missing keys and infrastructure failures are different cases. The request context carries the parent lifetime; the shorter local timeout bounds this particular operation.","code":"ctx, cancel := context.WithTimeout(requestCtx, 150*time.Millisecond)\ndefer cancel()\nvalue, err := client.Get(ctx, key).Result()\nswitch {\ncase errors.Is(err, redis.Nil):\n    // Cache miss: use the documented fallback.\ncase err != nil:\n    return fmt.Errorf(\"cache lookup: %w\", err)\ndefault:\n    use(value)\n}","language":"go","title":"Give each operation a bounded lifetime","walkthrough":"150 ms is an example, not a universal Redis timeout. Configure and verify client network timeouts as well; do not assume a context deadline replaces every transport setting."},{"body":"Pipelining can reduce network round trips, but an enormous pipeline can increase queued work and memory. Bound batch size and total payload, avoid broad scans or expensive hot-path commands, and monitor server latency, errors, pool waits and command volume. Test fallback behavior too: when the cache slows, a sudden flood of misses can overload the database behind it.","title":"Batch for efficiency without removing limits"}],"takeaway":"Limit work before it reaches Redis. A pool, timeout, rate limiter and bounded pipeline solve different parts of the capacity problem.","title":"Redis is fast; its capacity is still finite","unitID":"services","wrongAnswers":["Limits every connection to exactly one request per second","Provides one global connection budget across all replicas"]},{"conceptTag":"services.capacity","hint":"Follow one expired hot key through every replica and retry layer.","id":"services.cache-stampede","introduction":"A cache is often added to reduce load, yet its failure path can multiply load. When a popular key expires, many callers may fetch the same value at once. When a timeout triggers retries at several layers, one user action can become many downstream operations.","nuance":"An in-flight duplicate suppressor is neither a persistent cache nor a distributed lock.","objective":"Design a cache-miss path that avoids multiplying identical work and ambiguous retries.","question":"Which statement is correct about singleflight.group?","references":["https://pkg.go.dev/golang.org/x/sync/singleflight","https://redis.io/docs/latest/develop/clients/go/produsage/"],"reviewAnswer":"Coalesces in-flight work per key within one process","reviewPrompt":"singleflight.Group","sections":[{"body":"singleflight lets concurrent callers for the same key share one in-flight computation. The loader should have an explicit bounded lifetime. In this fragment loadCtx is owned by the service, not borrowed indefinitely from whichever request happened to arrive first.","code":"result, err, _ := group.Do(key, func() (any, error) {\n    ctx, cancel := context.WithTimeout(loadCtx, time.Second)\n    defer cancel()\n    return loadFromStore(ctx, key)\n})\nif err != nil { return err }\nuse(result)","language":"go","title":"Collapse duplicate work within a process","walkthrough":"group is a shared singleflight.Group. This synchronous form waits for the shared result; callers that must independently stop waiting need a cancellation-aware design, for example DoChan with a select. Coalescing is per process, not a distributed lock across replicas."},{"body":"Choose TTLs from the data contract. Jitter can spread expirations, but it does not make stale data acceptable automatically. Serving a stale value may be useful for a catalogue and wrong for an authorization decision. Bound key count and value size, and ensure a miss cannot start unlimited fallback work.","title":"Define cache freshness and failure policy"},{"body":"Use a small attempt budget, backoff with jitter and an overall deadline. A timed-out write may already have committed, so an automatic retry can duplicate a side effect without an idempotency contract. Coordinate retries at one layer where possible. Record attempts and final outcomes so apparent success does not conceal amplified downstream load.","title":"Retry only a retryable, safe operation"}],"takeaway":"Coalesce duplicates, bound fallback work and retry under an explicit contract. A faster happy path does not excuse an unbounded failure path.","title":"Cache misses, retries and overload amplification","unitID":"services","wrongAnswers":["All replicas and all Redis clients worldwide","Every completed request forever, like a persistent cache"]},{"conceptTag":"architecture.boundaries","designGuide":{"cautions":["A folder name does not enforce a boundary","Generic utils packages accumulate unrelated dependencies"],"cost":"Low to medium","family":"Architecture foundations","flow":["Consumer states a responsibility","Package exposes a focused API","Implementation details stay internal"],"ratings":[],"strengths":["A package has one clear reason to change","Import direction can be reviewed and tested"]},"hint":"Describe the caller's required behavior before naming the implementation.","id":"architecture.package-boundaries","introduction":"Go packages provide namespaces and compile-time dependency boundaries. More packages do not automatically create a cleaner design. Start with behavior that changes together, then separate a boundary when it hides an implementation detail or makes a dependency direction clearer.","nuance":"A directory tree is not architecture unless dependencies and responsibilities actually follow its boundaries.","objective":"Choose cohesive package boundaries and keep concrete dependencies at the edges.","question":"Which statement is correct about a consumer-owned interface?","references":["https://go.dev/doc/modules/layout","https://go.dev/doc/effective_go#interfaces"],"reviewAnswer":"Names the behavior its caller needs from a dependency","reviewPrompt":"A consumer-owned interface","sections":[{"body":"A package named orders can expose orders.Service or orders.Create without repeating a business prefix everywhere. A package called utils tends to accumulate unrelated dependencies because its purpose does not constrain what belongs there. Prefer a name that explains why its exported operations belong together.","title":"Keep names useful at the call site"},{"body":"The application needs the operation Save, not every method of the database client. Define that need near the code that uses it, and inject an implementation when wiring the process.","code":"type OrderStore interface {\n    Save(context.Context, Order) error\n}\ntype Service struct { store OrderStore }\nfunc NewService(store OrderStore) *Service {\n    return &Service{store: store}\n}","language":"go","title":"Let the consumer name a small interface","walkthrough":"The concrete SQL or Redis adapter can satisfy this interface implicitly. Do not create an interface for every struct by habit; add it where substitution or a stable boundary is useful."},{"body":"HTTP handlers can depend on application operations; those operations should not need a router context. Keep protocol and storage types from spreading through every function. An internal directory can restrict which importers may use a package, but it does not make a design cohesive by itself. Watch for import cycles as a signal that responsibilities may be entangled.","title":"Review dependency direction"},{"body":"Start from changes the team makes together: placing an order, pricing it and persisting it. A package should expose the vocabulary needed by its callers, not its database layout. Put transport decoding in an adapter and business decisions behind a narrow application API. Draw arrows for actual Go imports: a cycle means responsibilities must move or a smaller contract must be introduced. Renaming directories to domain, service and repository does not remove coupling if every package imports one shared mutable model.","code":"cmd/shop/main.go\ninternal/orders/service.go\ninternal/orders/order.go\ninternal/postgres/orders.go\ninternal/httpapi/orders.go","language":"text","title":"Draw an import graph before a folder tree","walkthrough":"This is a focused layout or boundary fragment, not a second standalone program. Read it together with the complete worked example above."},{"body":"The internal directory limits which importers may use a package; it does not make methods or data private between sibling packages. Unexport identifiers that clients do not need. Keep reusable libraries outside internal only when they have real independent consumers and a compatibility policy. Avoid a util package that accumulates unrelated helpers: move a helper beside its consumer until two callers reveal one coherent abstraction. Package boundaries and module version boundaries solve different problems.","title":"Use internal without promising more than it enforces"},{"body":"Imagine replacing Postgres with a fake for a service test. If the service imports SQL row types, the dependency crosses the intended boundary. Then imagine adding one order rule: it should be tested without HTTP. Finally inspect exported names with go doc and examine direct dependencies with go list. A good boundary makes these changes local; it does not require a dedicated interface and a separate file for every type. Record the ownership rule in package documentation so the next feature can preserve it.","title":"Check a boundary with a change experiment"}],"takeaway":"A good boundary reduces what a caller must know. Use cohesive packages and small consumer-owned contracts where they remove real coupling.","title":"Packages follow responsibilities, not a diagram","unitID":"architecture","wrongAnswers":["In a universal package containing every database API","As a mandatory duplicate for every concrete type"]},{"conceptTag":"architecture.boundaries","designGuide":{"cautions":["Adapters still need real integration tests","A port per field creates unnecessary indirection"],"cost":"Medium","family":"Hexagonal architecture","flow":["Driving adapter translates input","Application use case owns its ports","Driven adapter implements an external operation"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["The same use case has CLI, HTTP or test drivers","Policy should be tested without a database"]},"hint":"Trace a single request rather than adding layers to an abstract diagram.","id":"architecture.ports-and-adapters","introduction":"Ports and adapters is a way to keep a use case independent of delivery and infrastructure details. It is useful when one behavior has several entry points or storage implementations. The value comes from dependency direction, not from the number of folders named domain.","nuance":"Mocking a dependency tests a contract in isolation; it does not verify the concrete adapter honors that contract.","objective":"Trace an HTTP adapter through an application operation to a storage port and compare test boundaries.","question":"Which statement is correct about a storage port?","references":["https://go.dev/doc/effective_go#interfaces","https://pkg.go.dev/database/sql#Tx","https://alistair.cockburn.us/hexagonal-architecture","https://go.dev/doc/modules/layout"],"reviewAnswer":"Expresses a use case need independently of the database","reviewPrompt":"A storage port","sections":[{"body":"A request body becomes a CreateOrder command. The application validates business rules and calls an OrderStore port. The HTTP adapter translates the outcome back into protocol terms. The storage adapter translates the port operation into its own database protocol. Domain rules do not inspect HTTP headers or SQL row objects.","title":"Trace one operation"},{"body":"This example is an application fragment. Validation runs before persistence. The error receives operation context while the caller retains access to its cause.","code":"func (s *Service) Create(ctx context.Context, order Order) error {\n    if err := order.Validate(); err != nil {\n        return err\n    }\n    if err := s.store.Save(ctx, order); err != nil {\n        return fmt.Errorf(\"save order: %w\", err)\n    }\n    return nil\n}","language":"go","title":"Keep orchestration readable","walkthrough":"The interface does not define transaction semantics by magic. If creating an order and publishing an event must be atomic, design that consistency boundary explicitly, for example with a database transaction and an outbox."},{"body":"A fake store can test the use case cheaply, but cannot prove that a SQL adapter writes the right schema. Add integration tests for adapters and a smaller number of end-to-end journeys. Keep fakes faithful to important failure contracts, including cancellation and duplicate requests. Avoid adding layers when a small program has no substitution or ownership problem to solve.","title":"Test at more than one boundary"},{"body":"The application asks for a capability such as reserving inventory, not for a generic database connection. Define the smallest interface that the application consumes, with domain values and context.Context for work that can block. A SQL adapter implements that contract; a test fake implements the same observable behavior. The executable constructs the adapter and injects it into the use case. The port does not import HTTP, SQL drivers or framework types. One struct can implement several consumer-specific interfaces without declaring it explicitly.","title":"Put the port beside the use case"},{"body":"A repository adapter can translate sql.ErrNoRows into the application absence contract instead of leaking SQL details. An HTTP adapter maps that stable error category to a response and logs once. If a use case changes several records atomically, expose one transaction-scoped operation or unit-of-work boundary whose lifetime the use case controls. Calling three repository methods independently does not create a transaction. Keep a remote payment request outside a long database transaction and design reconciliation for a payment that succeeds before local persistence fails.","title":"Map errors and transactions deliberately"},{"body":"A fake that always returns success can hide wrong SQL behavior. Run a shared repository contract against both fake and real adapter: missing record, duplicate identifier, cancellation and commit failure matter. Use application tests for business rules and adapter tests for SQL mapping. The extra abstraction earns its place when rules outlive a transport or infrastructure choice; a small read-only command can call one concrete implementation directly and introduce a port later.","title":"Test the contract, not just the fake"}],"takeaway":"Use a port to express an application need and an adapter to translate an external mechanism. Verify both the use case and the concrete boundary.","title":"Ports and adapters with a real request","unitID":"architecture","wrongAnswers":["Every table and wire command used by all databases","An automatic transaction spanning unrelated external services"]},{"conceptTag":"architecture.design","designGuide":{"cautions":["Ratings are editorial starting points, not benchmarks","DDD, CQRS and deployment styles describe different axes"],"cost":"Depends on the chosen style","family":"Architecture decision guide","flow":["State the quality goal and constraints","Compare ownership, consistency and deployment costs","Record a decision and a measurable revisit trigger"],"ratings":[],"strengths":["A team needs to explain why a style fits","Architecture should evolve with evidence"]},"hint":"Compare the cost of a boundary with the change it makes easier.","id":"architecture.styles-and-clean-code","introduction":"Architecture is a choice about boundaries, change and failure. A modular monolith can keep strong internal boundaries with one deployment. Microservices can separate ownership and release schedules, but add remote calls, distributed failures, versioning and operational work.","nuance":"Distribution adds failure modes and operational work; it is not a prerequisite for clean Go code.","objective":"Compare a modular monolith, layered design and microservices using concrete operational tradeoffs.","question":"Which statement is correct about a modular monolith?","references":["https://go.dev/doc/effective_go","https://go.dev/doc/modules/layout"],"reviewAnswer":"Keeps module boundaries in one deployable process","reviewPrompt":"A modular monolith","sections":[{"body":"A small team sharing one transaction model may benefit from one deployable process with cohesive packages. Separate services become useful when independent scaling, ownership or delivery outweighs coordination costs. A folder named services does not make a monolith distributed, and a network hop does not make a boundary clean.","title":"Choose the smallest useful distribution boundary"},{"body":"Early returns keep a short function focused on its successful operation. Names should explain domain meaning; return errors at the layer able to add useful context. Avoid a generic helper that hides the important policy decision from its caller.","code":"func Ship(order Order) error {\n    if order.Cancelled {\n        return ErrCancelled\n    }\n    if !order.Paid {\n        return ErrUnpaid\n    }\n    return reserveShipment(order)\n}","language":"go","title":"Make the normal path visible","walkthrough":"This fragment makes the ordering of policy checks explicit. The real operation still needs an atomicity and idempotency contract if reservation changes external state. Shorter code is not cleaner when it conceals those obligations."},{"body":"Ask whether one business change requires edits across unrelated packages; whether error ownership is clear; whether interfaces have real consumers; and whether tests describe observable behavior instead of private function calls. Keep formatting with gofmt, document surprising contracts, and remove abstractions that do not pay for their indirection. No architecture style eliminates concurrency, capacity or consistency tradeoffs.","title":"Use a change-oriented checklist"},{"body":"Monolith and microservices describe deployment and ownership boundaries. Layered, hexagonal, Clean and Onion describe responsibility and source dependencies. Vertical slices organize change around features; MVC organizes presentation. DDD is a modeling approach, CQRS separates write and read models, and event sourcing chooses a state history as authority. A modular monolith can use hexagonal ports, vertical slices and CQRS together. Record the quality goal before comparing scores.","title":"Compare decisions on the same axis"},{"body":"First choose code organization: packages by capability, layers or vertical slices. Next choose state coordination: local transactions, asynchronous events or event history. Finally choose deployment topology: one executable, functions or independent services. These are different axes. A modular monolith can use hexagonal boundaries and CQRS; a microservice can still have tangled internal code. Describe the constraint a choice solves before comparing editorial ratings. Scores are scenario-specific recommendations, not performance measurements.","title":"Separate three architecture questions"},{"body":"A useful decision record contains the workload, team ownership, correctness requirements, candidate approaches, chosen tradeoff and what evidence would reopen the decision. For a small team, one deployable with local transactions may beat independently deployable services despite an ambitious diagram. Revisit when measured scaling, fault isolation or team release independence becomes a constraint. Do not migrate because a style receives a higher score in a different scenario.","title":"Write an architecture decision with an exit condition"},{"body":"Review one request from input validation to durable effect and response. Who owns the transaction? Who retries? Where is authorization enforced? Which boundary receives a deadline, and which log identifies the operation without exposing credentials? Then inspect tests at these seams. Small functions alone cannot repair contradictory ownership or undefined failure recovery. Prefer the simplest architecture that makes the required guarantees testable and operationally understandable.","title":"Make quality visible at the seams"}],"takeaway":"Choose boundaries for real change and ownership needs. Clear names, explicit errors, narrow contracts and behavioral tests matter in every architecture style.","title":"Choose a style; keep the code easy to change","unitID":"architecture","wrongAnswers":["It must expose every internal operation over a network","It cannot have independent modules or tests"]},{"conceptTag":"architecture.simple-monolith","designGuide":{"cautions":["A growing main package can mix unrelated responsibilities","One release coordinates every component"],"cost":"Low","family":"Architecture","flow":["Input at main","Local calculation","Result in the same process"],"ratings":[{"scenario":"Small tool or CLI","score":5},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":1}],"strengths":["A small team ships one useful workflow","Local calls and one deployment keep debugging direct"]},"hint":"The entry point decides how to report failure; total only parses and computes. The result is 36. There is no remote call, queue or dependency container because this variation has not appeared in the problem.","id":"architecture.simple-monolith","introduction":"Keep a small application understandable without premature service boundaries. A command-line invoice tool can parse input, compute a result and print it in one process. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Start splitting when different responsibilities change independently or teams need ownership boundaries.","objective":"Keep a small application understandable without premature service boundaries.","question":"Which statement best describes Simple monolith: start with one executable?","references":["https://go.dev/doc/modules/layout"],"reviewAnswer":"One process with explicit local responsibilities","reviewPrompt":"Simple monolith","sections":[{"body":"A command-line invoice tool can parse input, compute a result and print it in one process. Functions can separate these responsibilities before packages or network services become useful. One deployment is an operational choice; it does not require one giant function or prevent later modules.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc total(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn n * 12, nil\n}\n\nfunc main() {\n\tn, err := total(\"3\")\n\tif err != nil {\n\t\tfmt.Println(\"invalid quantity\")\n\t\treturn\n\t}\n\tfmt.Println(n)\n}\n\n// Output:\n// 36\n","language":"go","title":"A complete Go example","walkthrough":"The entry point decides how to report failure; total only parses and computes. The result is 36. There is no remote call, queue or dependency container because this variation has not appeared in the problem."},{"body":"Start splitting when different responsibilities change independently or teams need ownership boundaries. A simple monolith can scale through replicas; shared mutable state and database contention still need measurement. Avoid hiding every function behind an interface.","title":"Tradeoffs and the simpler alternative"},{"body":"Keep main responsible for configuration, dependency construction, startup and graceful shutdown. Pass dependencies into handlers rather than hiding them in package globals. Place use cases behind package APIs even if there is only one executable. This retains fast local calls and a single operational unit while allowing multiple entry points later. A monolith describes deployment; it does not require a single package or prevent good isolation inside the process.","title":"Build one process with explicit composition"},{"body":"Order creation and inventory reservation can commit in one database transaction when they share a consistency boundary. Validate cheap input before opening that transaction, avoid network calls while holding locks and roll back on every failure path. A successful HTTP response should follow the required durable commit, not precede it. If an email must eventually follow the commit, record an outbox item atomically and process it later; sending email first cannot be rolled back with the database.","title":"Use local transactions as a strength"},{"body":"Measure request latency, database time, queue depth and memory before extracting services. A process can have multiple replicas and background workers while remaining a monolith, provided shared state is durable and concurrency-safe. Start by improving indexes or isolating a slow worker. If one capability later needs independent deployment, keep its existing API and extract behind that seam. Expect remote timeouts and partial failure to become new work after extraction.","title":"Scale only the measured bottleneck"},{"body":"Start splitting when different responsibilities change independently or teams need ownership boundaries. A simple monolith can scale through replicas; shared mutable state and database contention still need measurement. Avoid hiding every function behind an interface.","title":"Practical limits and cautions"}],"takeaway":"One process with explicit local responsibilities. Start splitting when different responsibilities change independently or teams need ownership boundaries. A simple monolith can scale through replicas; shared mutable state and database contention still need measurement. Avoid hiding every function behind an interface.","title":"Simple monolith: start with one executable","unitID":"architecture","wrongAnswers":["A network hop for every function","A requirement to keep all code in main"]},{"conceptTag":"architecture.layered","designGuide":{"cautions":["Features can require edits across several layers","Thin pass-through layers add ceremony"],"cost":"Medium","family":"Architecture","flow":["Transport decodes input","Application validates a use case","Storage persists data"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["A service has distinct request and storage concerns","A team benefits from a predictable call path"]},"hint":"Register enforces a rule before Store changes.","id":"architecture.layered","introduction":"Separate responsibilities without confusing logical layers with deployed tiers. A layered service routes requests through transport, application logic and persistence. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"A feature may touch every horizontal layer, so keep mapping work proportional to the value it protects.","objective":"Separate responsibilities without confusing logical layers with deployed tiers.","question":"Which statement best describes Layered architecture: transport, application, storage?","references":["https://go.dev/doc/modules/layout"],"reviewAnswer":"Separate responsibilities without requiring network tiers","reviewPrompt":"Logical layers","sections":[{"body":"A layered service routes requests through transport, application logic and persistence. Logical layers may live in the same executable. Avoid a handler bypassing validation to write directly to storage, and avoid pass-through types that only rename the next function.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Store struct{ names []string }\n\nfunc (s *Store) Save(name string) { s.names = append(s.names, name) }\n\ntype Service struct{ store *Store }\n\nfunc (s Service) Register(name string) error {\n\tif name == \"\" {\n\t\treturn errors.New(\"name required\")\n\t}\n\ts.store.Save(name)\n\treturn nil\n}\n\nfunc main() {\n\tstore := &Store{}\n\tservice := Service{store: store}\n\tfmt.Println(service.Register(\"Ada\"))\n\tfmt.Println(store.names)\n}\n\n// Output:\n// <nil>\n// [Ada]\n","language":"go","title":"A complete Go example","walkthrough":"Register enforces a rule before Store changes. main acts as the transport for this small example and prints success followed by the stored name. Concrete dependencies are enough here; a boundary interface can be introduced when there is a caller need."},{"body":"A feature may touch every horizontal layer, so keep mapping work proportional to the value it protects. Layering alone does not invert dependencies, create transactions or make storage replaceable. A single function is simpler for a one-off script.","title":"Tradeoffs and the simpler alternative"},{"body":"Model–View–Controller separates a model of state and behavior, a view that renders output, and a controller that translates user input into operations. A Go web handler can act as a controller and a template as the view. This does not require a database model for every view, nor does it decide whether the application is one process or many services. Keep business invariants outside presentation formatting; use html/template rather than concatenating untrusted HTML.","title":"MVC is a presentation organization"},{"body":"An HTTP layer decodes a request and maps a response; an application layer executes a use case; a storage adapter persists its state. The application should receive typed intent, not an http.Request. Likewise, database rows should not automatically become public JSON. Separate request DTOs from domain values when their validation and compatibility rules differ. Avoid a layer whose only purpose is forwarding every call unchanged to another layer.","title":"Trace dependency direction through a real request"},{"body":"A transaction belongs to the complete use case, such as moving funds between accounts. Starting and committing inside each repository method makes the two balance changes independent. Pass transaction-scoped capabilities to the use case or offer one atomic domain operation. Keep validation errors distinct from infrastructure failures, and do not convert every failure into a nil result. A layered diagram does not itself establish atomicity, authorization or idempotency.","title":"Put the transaction around the business operation"},{"body":"If one small feature repeatedly changes controller, manager, service, repository and mapper with no distinct decision in most layers, collapse unnecessary forwarding. Organize files by feature within a layer or introduce a vertical slice. Preserve stable cross-cutting policy such as authentication at a clear boundary. Test each layer only for the behavior it owns: request mapping, business invariant or persistence contract, rather than duplicating the same happy-path assertion five times.","title":"Reduce horizontal change amplification"},{"body":"A feature may touch every horizontal layer, so keep mapping work proportional to the value it protects. Layering alone does not invert dependencies, create transactions or make storage replaceable. A single function is simpler for a one-off script.","title":"Practical limits and cautions"},{"body":"Register enforces a rule before Store changes. main acts as the transport for this small example and prints success followed by the stored name. Concrete dependencies are enough here; a boundary interface can be introduced when there is a caller need.","title":"How to read this example"}],"takeaway":"Separate responsibilities without requiring network tiers. A feature may touch every horizontal layer, so keep mapping work proportional to the value it protects. Layering alone does not invert dependencies, create transactions or make storage replaceable. A single function is simpler for a one-off script.","title":"Layered architecture: transport, application, storage","unitID":"architecture","wrongAnswers":["One server per package","Automatic dependency inversion"]},{"conceptTag":"architecture.modular-monolith","designGuide":{"cautions":["One deployment still couples release timing","Shared tables can erode module ownership"],"cost":"Medium","family":"Architecture","flow":["Composition root wires modules","Shipping calls a billing query","Billing keeps its state private"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":3}],"strengths":["Business boundaries are clearer than infrastructure boundaries","One team wants local calls and coordinated transactions"]},"hint":"Shipping receives the one query it needs instead of the billing map. Both calls stay in the same process. In a real module layout these declarations belong in separate packages, with internal implementation hidden behind each module API.","id":"architecture.modular-monolith","introduction":"Give business capabilities explicit APIs while retaining local transactions. A modular monolith groups capabilities such as billing and shipping behind package APIs. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"One database can support atomic changes, but bypassing module APIs destroys ownership.","objective":"Give business capabilities explicit APIs while retaining local transactions.","question":"Which statement best describes Modular monolith: boundaries inside one deployment?","references":["https://go.dev/doc/modules/layout","https://martinfowler.com/articles/microservice-trade-offs.html"],"reviewAnswer":"Business capabilities expose APIs in one deployment","reviewPrompt":"Modular ownership","sections":[{"body":"A modular monolith groups capabilities such as billing and shipping behind package APIs. Keep their implementation and tables private by convention and review. A module is not an excuse for another global models package that every feature can mutate.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Billing struct{ paid map[string]bool }\n\nfunc (b Billing) IsPaid(id string) bool { return b.paid[id] }\n\ntype Shipping struct{ paid func(string) bool }\n\nfunc (s Shipping) CanShip(id string) bool { return s.paid(id) }\n\nfunc main() {\n\tbilling := Billing{paid: map[string]bool{\"order-1\": true}}\n\tshipping := Shipping{paid: billing.IsPaid}\n\tfmt.Println(shipping.CanShip(\"order-1\"))\n\tfmt.Println(shipping.CanShip(\"order-2\"))\n}\n\n// Output:\n// true\n// false\n","language":"go","title":"A complete Go example","walkthrough":"Shipping receives the one query it needs instead of the billing map. Both calls stay in the same process. In a real module layout these declarations belong in separate packages, with internal implementation hidden behind each module API."},{"body":"One database can support atomic changes, but bypassing module APIs destroys ownership. Enforce dependency direction with package boundaries and review. Extract a service only when independent scaling, release cadence or isolation pays for remote failures.","title":"Tradeoffs and the simpler alternative"},{"body":"Billing can expose IsPaid or ConfirmPayment without exporting its payment map or SQL tables. Shipping asks the billing API instead of reading billing tables directly. A practical layout puts each capability below internal with a small exported surface and keeps application wiring in cmd. Go internal restricts outside imports but does not prevent sibling packages from bypassing ownership, so unexport implementation types and review dependencies. Sharing one database is an operational choice, not permission for every module to mutate every table.","title":"Turn capability ownership into package APIs"},{"body":"When two changes truly require one atomic transaction, define the coordinator and transaction-scoped operations explicitly. When they can be eventually consistent, commit the initiating change and an outbox record together, then apply the receiving action idempotently. Document what the user sees while shipping has not yet observed payment. An in-memory notification after commit can be lost if the process crashes, so it is not a substitute for a durable handoff.","title":"Choose consistency across module boundaries"},{"body":"A module is ready for service extraction when its contract, ownership and data access are already explicit. First find direct table reads, shared pointers and cross-module transactions; these are migration work. Put a network adapter behind the existing consumer contract and introduce timeouts, versioning and retry-safe operations. Run contract tests before switching traffic. Keep the monolith if the same team deploys everything together and local transactions still provide more value than independent release timing.","title":"Extract without breaking every caller"},{"body":"One database can support atomic changes, but bypassing module APIs destroys ownership. Enforce dependency direction with package boundaries and review. Extract a service only when independent scaling, release cadence or isolation pays for remote failures.","title":"Practical limits and cautions"}],"takeaway":"Business capabilities expose APIs in one deployment. One database can support atomic changes, but bypassing module APIs destroys ownership. Enforce dependency direction with package boundaries and review. Extract a service only when independent scaling, release cadence or isolation pays for remote failures.","title":"Modular monolith: boundaries inside one deployment","unitID":"architecture","wrongAnswers":["Every module must have a remote API","All modules may write each other’s tables"]},{"conceptTag":"architecture.clean-onion","designGuide":{"cautions":["More boundaries require deliberate mapping","A diagram cannot enforce business invariants"],"cost":"Medium to high","family":"Architecture","flow":["Outer adapter implements a port","Use case depends on the port","Domain computes the price"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["Business policy outlives transport and storage choices","Use cases need isolated tests"]},"hint":"Product performs policy without importing storage.","id":"architecture.clean-onion","introduction":"Keep domain policy independent of framework and database details. Clean and Onion designs place domain rules near the center and technology at the edge. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Model missing products and invalid discounts before using this mechanism in production.","objective":"Keep domain policy independent of framework and database details.","question":"Which statement best describes Clean and Onion: dependencies point toward policy?","references":["https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html","https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/","https://go.dev/doc/modules/layout"],"reviewAnswer":"Source dependencies point inward toward policy","reviewPrompt":"Clean dependency rule","sections":[{"body":"Clean and Onion designs place domain rules near the center and technology at the edge. Source imports point toward stable policy even when a runtime call goes outward through an interface. These related styles are not identical diagrams, and neither prescribes a Go folder template.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Product struct{ Price int }\n\nfunc (p Product) Discount(percent int) int { return p.Price * (100 - percent) / 100 }\n\ntype Prices interface{ Find(string) Product }\ntype Quote struct{ prices Prices }\n\nfunc (q Quote) Total(id string) int { return q.prices.Find(id).Discount(10) }\n\ntype MemoryPrices map[string]Product\n\nfunc (m MemoryPrices) Find(id string) Product { return m[id] }\n\nfunc main() {\n\tq := Quote{prices: MemoryPrices{\"book\": {Price: 200}}}\n\tfmt.Println(q.Total(\"book\"))\n}\n\n// Output:\n// 180\n","language":"go","title":"A complete Go example","walkthrough":"Product performs policy without importing storage. Quote depends on its own Prices contract. The outer MemoryPrices implementation satisfies it implicitly, and main wires the concrete choice. The inward source dependency differs from the runtime lookup direction."},{"body":"Model missing products and invalid discounts before using this mechanism in production. Do not create a DTO, interface and mapper for every struct automatically. For a tiny CRUD endpoint, a focused handler and explicit SQL may be easier to change.","title":"Tradeoffs and the simpler alternative"},{"body":"The dependency rule concerns source imports: policy types do not import a web framework or database driver. At runtime a use case can call an adapter through a consumer-owned interface even though the adapter imports the policy package. Wire concrete adapters in the composition root. Entities express invariants; application services coordinate a use case. Request validation and serialization stay at the outside, while domain validation remains enforceable when the same use case is called by a job or CLI.","title":"Distinguish imports from runtime calls"},{"body":"A constructor returning a concrete type is often appropriate. Introduce an interface where a consumer needs a replaceable capability, especially at IO and clock boundaries. Do not create a BaseRepository or service factory hierarchy just to imitate a class-oriented diagram. A pure calculation needs no repository. Repeated DTO conversions should protect a real boundary; when two layers use an identical stable value, copying every field solely to preserve a diagram adds cost without independence.","title":"Avoid an interface for every concrete type"},{"body":"Construct the application service with an in-memory contract implementation and a controlled clock. Check the invariant, failure result and absence of unwanted side effects. Then verify the production adapter separately against its real storage contract. If starting a router, database and message broker is required to test a price rule, policy still depends on infrastructure somewhere. Clean architecture suits long-lived business rules, while a short one-purpose tool may be clearer with fewer boundaries.","title":"Prove independence with a focused test"},{"body":"Model missing products and invalid discounts before using this mechanism in production. Do not create a DTO, interface and mapper for every struct automatically. For a tiny CRUD endpoint, a focused handler and explicit SQL may be easier to change.","title":"Practical limits and cautions"},{"body":"Product performs policy without importing storage. Quote depends on its own Prices contract. The outer MemoryPrices implementation satisfies it implicitly, and main wires the concrete choice. The inward source dependency differs from the runtime lookup direction.","title":"How to read this example"}],"takeaway":"Source dependencies point inward toward policy. Model missing products and invalid discounts before using this mechanism in production. Do not create a DTO, interface and mapper for every struct automatically. For a tiny CRUD endpoint, a focused handler and explicit SQL may be easier to change.","title":"Clean and Onion: dependencies point toward policy","unitID":"architecture","wrongAnswers":["Domain policy imports the web framework","Every value requires five mapped copies"]},{"conceptTag":"architecture.vertical-slice","designGuide":{"cautions":["Cross-feature invariants need explicit ownership","Uncontrolled duplication can drift"],"cost":"Medium","family":"Architecture","flow":["Rename request","RenameProject validation","Persist the renamed project"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":3}],"strengths":["Most changes affect one feature","A team wants short paths from endpoint to behavior"]},"hint":"RenameProject owns normalization and validation for one operation.","id":"architecture.vertical-slice","introduction":"Keep feature changes together without duplicating shared invariants. A vertical slice groups request parsing, application behavior and persistence for one capability, such as RenameProject. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Extract a shared domain rule when several slices genuinely enforce the same invariant.","objective":"Keep feature changes together without duplicating shared invariants.","question":"Which statement best describes Vertical slices: organize around a use case?","references":["https://go.dev/doc/modules/layout","https://www.jimmybogard.com/vertical-slice-architecture/"],"reviewAnswer":"Group code by use case and reason to change","reviewPrompt":"Vertical slice","sections":[{"body":"A vertical slice groups request parsing, application behavior and persistence for one capability, such as RenameProject. It can live inside a modular monolith and still call shared domain rules. It describes organization by change, not a new deployment topology.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Project struct{ Name string }\n\nfunc RenameProject(p *Project, raw string) error {\n\tname := strings.TrimSpace(raw)\n\tif name == \"\" {\n\t\treturn errors.New(\"name required\")\n\t}\n\tp.Name = name\n\treturn nil\n}\n\nfunc main() {\n\tp := Project{Name: \"Draft\"}\n\tfmt.Println(RenameProject(&p, \"  Library  \"))\n\tfmt.Println(p.Name)\n}\n\n// Output:\n// <nil>\n// Library\n","language":"go","title":"A complete Go example","walkthrough":"RenameProject owns normalization and validation for one operation. The caller receives an error rather than modifying Name itself. A larger slice can include its HTTP DTO and SQL query without routing through layers that only forward arguments."},{"body":"Extract a shared domain rule when several slices genuinely enforce the same invariant. Duplicated validation can drift, while an overgeneralized framework can make every change harder. Slices can share infrastructure without sharing their entire application model.","title":"Tradeoffs and the simpler alternative"},{"body":"Keep the command or query, validation, handler and response mapping for PlaceOrder close together. Share domain rules when they genuinely apply across use cases, not because two DTOs happen to have similar fields. A slice can use a concrete store for a simple query and a richer domain model for a complex command. Vertical slices describe the direction of code organization; they can run in one process and do not imply a service for each endpoint.","title":"Organize by the change a user requests"},{"body":"Authentication, authorization, observability and transaction management should have one understandable integration point. Keep endpoint-specific authorization near the use case when permission depends on loaded domain state. Avoid a global pipeline that catches and suppresses every error or makes transaction lifetime invisible. Two slices updating the same invariant need coordinated ownership, even if their files are in separate folders. Duplicating business rules across slices creates divergent behavior.","title":"Make shared policy explicit"},{"body":"For a command, test invalid input, denied access, success and a failed durable write. For a query, test filtering and response shape without constructing unrelated domain workflows. Preserve the public route and event contracts while reorganizing packages. Extract shared code only after repeated changes reveal one stable responsibility. This approach makes feature changes local but needs conventions so each slice does not invent different error, logging and validation behavior.","title":"Test one slice end to end at its boundary"},{"body":"Extract a shared domain rule when several slices genuinely enforce the same invariant. Duplicated validation can drift, while an overgeneralized framework can make every change harder. Slices can share infrastructure without sharing their entire application model.","title":"Practical limits and cautions"},{"body":"RenameProject owns normalization and validation for one operation. The caller receives an error rather than modifying Name itself. A larger slice can include its HTTP DTO and SQL query without routing through layers that only forward arguments.","title":"How to read this example"}],"takeaway":"Group code by use case and reason to change. Extract a shared domain rule when several slices genuinely enforce the same invariant. Duplicated validation can drift, while an overgeneralized framework can make every change harder. Slices can share infrastructure without sharing their entire application model.","title":"Vertical slices: organize around a use case","unitID":"architecture","wrongAnswers":["A separate database for every function","A ban on shared domain rules"]},{"conceptTag":"architecture.ddd","designGuide":{"cautions":["Modeling requires collaboration with domain experts","Concurrency needs persistence-level enforcement"],"cost":"High","family":"Architecture","flow":["Context defines vocabulary","Aggregate validates a command","Repository persists atomically"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["Business rules change frequently","Different domains use the same word differently"]},"hint":"The Basket operation checks the invariant before mutation, so a rejected addition leaves three items.","id":"architecture.ddd","introduction":"Model language and invariants before choosing storage or transport. Domain-driven design is a modeling approach, not a demand for microservices. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use richer models where business language and rules justify them.","objective":"Model language and invariants before choosing storage or transport.","question":"Which statement best describes DDD: bounded contexts and aggregates?","references":["https://www.domainlanguage.com/ddd/reference/","https://go.dev/doc/modules/layout"],"reviewAnswer":"Protects invariants within a consistency boundary","reviewPrompt":"DDD aggregate","sections":[{"body":"Domain-driven design is a modeling approach, not a demand for microservices. A bounded context defines where a model and its language apply. An aggregate protects a consistency boundary: its public operations should prevent invalid state transitions.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Basket struct{ items int }\n\nfunc (b *Basket) Add(quantity int) error {\n\tif quantity <= 0 {\n\t\treturn errors.New(\"positive quantity required\")\n\t}\n\tif b.items+quantity > 10 {\n\t\treturn errors.New(\"basket limit\")\n\t}\n\tb.items += quantity\n\treturn nil\n}\n\nfunc main() {\n\tb := &Basket{}\n\tfmt.Println(b.Add(3))\n\tfmt.Println(b.Add(8))\n\tfmt.Println(b.items)\n}\n\n// Output:\n// <nil>\n// basket limit\n// 3\n","language":"go","title":"A complete Go example","walkthrough":"The Basket operation checks the invariant before mutation, so a rejected addition leaves three items. This illustrates an aggregate rule, not durable storage. Concurrent database writes need transactions or version checks to preserve the same invariant."},{"body":"Use richer models where business language and rules justify them. A reporting query can return a projection without reconstructing every aggregate. Too many tiny entities and repositories obscure straightforward CRUD; bounded contexts can remain packages in one executable.","title":"Tradeoffs and the simpler alternative"},{"body":"A value object is defined by its value, while an entity has identity over time. An aggregate is a consistency boundary whose root protects invariants, not a graph of everything related by a foreign key. For an order, accepting a line may check quantity and price rules before mutation. Keep those rules enforceable without an HTTP handler. A bounded context defines where terms have one meaning: customer in billing need not be the same model as customer in support.","title":"Model invariants before naming entities"},{"body":"Keep a transaction small enough to protect the invariant it owns. If placing an order and reserving remote stock cannot be atomic, model pending, confirmed and rejected states and define compensating actions. Use version checks when concurrent writers can otherwise overwrite each other. Domain events describe facts that already happened; publishing them durably requires an outbox or another defined handoff. Calling a broker in the middle of mutation does not make the database and broker commit together.","title":"Coordinate aggregates with explicit consistency"},{"body":"Start with scenarios from domain experts and encode examples as tests: duplicate line, cancelled order, price change and concurrent update. CRUD administration often needs a simple data model rather than repositories, aggregates and domain services. Introduce an anti-corruption adapter when integrating a foreign model so its vocabulary does not leak everywhere. DDD has a high communication and modeling cost; it pays when rules and language are complex, not merely when a project has many tables.","title":"Use domain modeling selectively"},{"body":"Use richer models where business language and rules justify them. A reporting query can return a projection without reconstructing every aggregate. Too many tiny entities and repositories obscure straightforward CRUD; bounded contexts can remain packages in one executable.","title":"Practical limits and cautions"},{"body":"The Basket operation checks the invariant before mutation, so a rejected addition leaves three items. This illustrates an aggregate rule, not durable storage. Concurrent database writes need transactions or version checks to preserve the same invariant.","title":"How to read this example"}],"takeaway":"Protects invariants within a consistency boundary. Use richer models where business language and rules justify them. A reporting query can return a projection without reconstructing every aggregate. Too many tiny entities and repositories obscure straightforward CRUD; bounded contexts can remain packages in one executable.","title":"DDD: bounded contexts and aggregates","unitID":"architecture","wrongAnswers":["A synonym for a separately deployed service","A requirement to model every SQL row as an aggregate"]},{"conceptTag":"architecture.cqrs","designGuide":{"cautions":["Async projections introduce lag and rebuild work","Simple CRUD may gain only extra types"],"cost":"Medium to high","family":"Architecture","flow":["Command validates a change","Authoritative state changes","Query returns a read model"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":4}],"strengths":["Writes have rules and reads need different shapes","Read scaling has a measured need"]},"hint":"Deposit is the command boundary; Summary is the query shape. Both read the same in-memory state here, so there is no projection lag. Separating methods does not by itself require queues, extra services or event replay.","id":"architecture.cqrs","introduction":"Separate change rules from read shape without assuming two databases. CQRS separates the model that changes state from the model that answers questions. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"If a projection becomes asynchronous, explain stale reads and rebuild procedures to clients and operators.","objective":"Separate change rules from read shape without assuming two databases.","question":"Which statement best describes CQRS: different models for commands and queries?","references":["https://martinfowler.com/bliki/CQRS.html","https://go.dev/doc/modules/layout"],"reviewAnswer":"Separates the write model from the read model","reviewPrompt":"CQRS","sections":[{"body":"CQRS separates the model that changes state from the model that answers questions. Commands can protect invariants while queries return compact summaries. Start in one process and one database; asynchronous projections and event sourcing are optional additional decisions.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Ledger struct{ balance int }\n\nfunc (l *Ledger) Deposit(n int) error {\n\tif n <= 0 {\n\t\treturn errors.New(\"positive deposit required\")\n\t}\n\tl.balance += n\n\treturn nil\n}\n\ntype Summary struct{ Available int }\n\nfunc (l Ledger) Summary() Summary { return Summary{Available: l.balance} }\n\nfunc main() {\n\tl := &Ledger{}\n\t_ = l.Deposit(50)\n\tfmt.Println(l.Summary().Available)\n}\n\n// Output:\n// 50\n","language":"go","title":"A complete Go example","walkthrough":"Deposit is the command boundary; Summary is the query shape. Both read the same in-memory state here, so there is no projection lag. Separating methods does not by itself require queues, extra services or event replay."},{"body":"If a projection becomes asynchronous, explain stale reads and rebuild procedures to clients and operators. Ordinary CRUD may not need separate models. Add CQRS where read shapes and write rules diverge, rather than to make simple storage appear architectural.","title":"Tradeoffs and the simpler alternative"},{"body":"Commands express intent and validate invariants; queries return a shape optimized for a reader. Both can initially use the same process and database. A dashboard projection may join fields that never belong in the command aggregate. CQRS does not require event sourcing, a broker or separate databases. Keep authorization and sensitive-field filtering on the query path too: a read model is not automatically safe because it does not mutate state.","title":"Separate models before separating infrastructure"},{"body":"With an asynchronous projection, a successful command can be durable before the query model catches up. Return a command identifier or version and decide whether the UI waits for that version, shows pending state or reads a command result directly. Apply projection events idempotently and in the required order. Record a durable cursor; an in-memory last-seen marker cannot support restart. Deleted or corrected records need explicit projection behavior.","title":"Design projection lag as user-visible behavior"},{"body":"A projection test should apply duplicate input and verify it does not double-count. Test out-of-order events according to the chosen policy, a restart from the saved cursor and schema changes. Rebuild a new projection beside the old one, compare counts and representative queries, then switch readers. Separate read/write models when their needs differ enough to pay for synchronization. A small application with one ordinary CRUD shape can keep one model.","title":"Rebuild and test a projection"},{"body":"If a projection becomes asynchronous, explain stale reads and rebuild procedures to clients and operators. Ordinary CRUD may not need separate models. Add CQRS where read shapes and write rules diverge, rather than to make simple storage appear architectural.","title":"Practical limits and cautions"}],"takeaway":"Separates the write model from the read model. If a projection becomes asynchronous, explain stale reads and rebuild procedures to clients and operators. Ordinary CRUD may not need separate models. Add CQRS where read shapes and write rules diverge, rather than to make simple storage appear architectural.","title":"CQRS: different models for commands and queries","unitID":"architecture","wrongAnswers":["Always requires event sourcing","Always requires two databases"]},{"conceptTag":"architecture.event-sourcing","designGuide":{"cautions":["Replay and schema evolution need long-term support","External side effects need separate deduplication"],"cost":"Very high","family":"Architecture","flow":["Validate command against current state","Append events at an expected version","Replay events into state"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["Temporal reconstruction is a product requirement","Domain history must be explicit"]},"hint":"Replaying both events yields 30; replaying the prefix yields 50.","id":"architecture.event-sourcing","introduction":"Distinguish a source of truth from ordinary logs and notifications. An event-sourced aggregate reconstructs state from accepted domain events. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Choose this when temporal history and reconstruction are core requirements.","objective":"Distinguish a source of truth from ordinary logs and notifications.","question":"Which statement best describes Event sourcing: state from a durable history?","references":["https://martinfowler.com/eaaDev/EventSourcing.html","https://go.dev/doc/modules/layout"],"reviewAnswer":"Rebuilds authoritative state from accepted events","reviewPrompt":"Event-sourced state","sections":[{"body":"An event-sourced aggregate reconstructs state from accepted domain events. The event stream is authoritative, so event meaning and ordering must remain interpretable for years. This differs from logging what a conventional database already stored.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Event struct{ Delta int }\n\nfunc replay(events []Event) int {\n\tbalance := 0\n\tfor _, e := range events {\n\t\tbalance += e.Delta\n\t}\n\treturn balance\n}\n\nfunc main() {\n\tevents := []Event{{Delta: 50}, {Delta: -20}}\n\tfmt.Println(replay(events))\n\tfmt.Println(replay(events[:1]))\n}\n\n// Output:\n// 30\n// 50\n","language":"go","title":"A complete Go example","walkthrough":"Replaying both events yields 30; replaying the prefix yields 50. The slice only demonstrates deterministic reduction. A real event store also needs append version checks, durable writes, event schemas and a policy for replaying external side effects."},{"body":"Choose this when temporal history and reconstruction are core requirements. Replay must not resend emails or charge cards. Event evolution, privacy deletion and projection rebuilds are significant costs; an audit table is often enough for a conventional service.","title":"Tradeoffs and the simpler alternative"},{"body":"An event records a business fact such as OrderAccepted, with identity, aggregate sequence and event schema version. Replaying history applies facts without sending emails or charging cards again. Validate a command against the current aggregate state, decide new events, then append with an expected stream version. A read-then-append sequence without concurrency control can accept conflicting commands. Event sourcing stores state transitions as the source of truth; a message broker alone is not that event store.","title":"Treat event history as a durable contract"},{"body":"An old event cannot silently change meaning when a struct is renamed. Use version-aware decoders or explicit upcasting and retain replay fixtures from historical versions. A snapshot is a performance aid tied to a known event sequence, not a replacement for missing history. Avoid embedding secrets and unnecessary personal data in immutable events; deletion and retention obligations need a deliberate design. Do not describe immutable storage as automatically satisfying every audit requirement.","title":"Plan evolution, snapshots and sensitive data"},{"body":"An event handler updating a projection can be replayed; an external payment requires a durable idempotency key and side-effect policy. Test rebuilding an empty projection from the whole stream and compare state with incremental processing. Test conflicting expected versions and malformed historical events. Adopt event sourcing when historical reconstruction and domain behavior justify its substantial operational cost. An append-only audit log beside ordinary state may solve a simpler audit requirement more cheaply.","title":"Separate replay from external side effects"},{"body":"Choose this when temporal history and reconstruction are core requirements. Replay must not resend emails or charge cards. Event evolution, privacy deletion and projection rebuilds are significant costs; an audit table is often enough for a conventional service.","title":"Practical limits and cautions"},{"body":"Replaying both events yields 30; replaying the prefix yields 50. The slice only demonstrates deterministic reduction. A real event store also needs append version checks, durable writes, event schemas and a policy for replaying external side effects.","title":"How to read this example"}],"takeaway":"Rebuilds authoritative state from accepted events. Choose this when temporal history and reconstruction are core requirements. Replay must not resend emails or charge cards. Event evolution, privacy deletion and projection rebuilds are significant costs; an audit table is often enough for a conventional service.","title":"Event sourcing: state from a durable history","unitID":"architecture","wrongAnswers":["Replays payment side effects on every read","Means adding log messages to CRUD"]},{"conceptTag":"architecture.event-driven","designGuide":{"cautions":["Delivery duplicates and reordering need policies","Debugging spans queues and consumers"],"cost":"High","family":"Architecture","flow":["Producer commits an event or outbox record","Broker may redeliver","Consumer atomically records its effect"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":5}],"strengths":["Independent reactions should not block a request","Bursty work benefits from durable buffering"]},"hint":"Two deliveries of event-1 create one effect.","id":"architecture.event-driven","introduction":"Treat duplicate delivery as normal and define the durable boundary. Event-driven systems decouple a producer from consumers through notifications or durable messages. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Buffering can isolate timing, but it does not guarantee business completion.","objective":"Treat duplicate delivery as normal and define the durable boundary.","question":"Which statement best describes Event-driven services: delivery and idempotency?","references":["https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/event-driven","https://go.dev/doc/modules/layout"],"reviewAnswer":"Repeating a message does not repeat its business effect","reviewPrompt":"Idempotent consumer","sections":[{"body":"Event-driven systems decouple a producer from consumers through notifications or durable messages. Consumers should know what happened and decide their own reaction. Delivery can repeat, so the design needs event identities, ordering rules and a durable acknowledgment strategy.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Consumer struct {\n\tseen  map[string]bool\n\tcount int\n}\n\nfunc (c *Consumer) Handle(id string) {\n\tif c.seen[id] {\n\t\treturn\n\t}\n\tc.seen[id] = true\n\tc.count++\n}\n\nfunc main() {\n\tc := Consumer{seen: make(map[string]bool)}\n\tc.Handle(\"event-1\")\n\tc.Handle(\"event-1\")\n\tc.Handle(\"event-2\")\n\tfmt.Println(c.count)\n}\n\n// Output:\n// 2\n","language":"go","title":"A complete Go example","walkthrough":"Two deliveries of event-1 create one effect. This single-goroutine memory map demonstrates deduplication only. Production deduplication must commit the event identity and business effect atomically; otherwise a crash can lose work or repeat the effect."},{"body":"Buffering can isolate timing, but it does not guarantee business completion. Define dead-letter handling, retry limits and observability. A transactional outbox can bridge a database commit and later publication; a plain goroutine cannot replace durable messaging.","title":"Tradeoffs and the simpler alternative"},{"body":"A producer commits a business change and an outbox record in one transaction. A relay publishes the record and may publish it again after a crash. The consumer therefore needs a stable event identifier and an idempotent effect. Acknowledge only after the required durable work. At-least-once delivery is not exactly-once business processing: a payment gateway, email API and local store do not share one magical commit.","title":"Specify the delivery contract"},{"body":"Order events only where the business needs it, often per aggregate rather than globally. Bound retries with backoff and jitter, and route repeated failures to a monitored dead-letter path with a replay procedure. Distinguish invalid events from temporary infrastructure outages. A permanently malformed message should not block unrelated work forever. Version event schemas compatibly and include correlation identifiers without leaking tokens or personal payloads into logs.","title":"Choose ordering, retries and a poison-message path"},{"body":"Test a crash after database commit but before publish, after publish but before marking the outbox sent, and after the consumer effect but before acknowledgement. Verify duplicates do not repeat the effect and that lag is visible in metrics. Monitor oldest unprocessed age, backlog and failure count, not only whether the worker process is alive. Use events for meaningful decoupling; a synchronous local call is clearer when a caller needs an immediate answer and no durable handoff.","title":"Exercise the crash windows"},{"body":"Buffering can isolate timing, but it does not guarantee business completion. Define dead-letter handling, retry limits and observability. A transactional outbox can bridge a database commit and later publication; a plain goroutine cannot replace durable messaging.","title":"Practical limits and cautions"},{"body":"Two deliveries of event-1 create one effect. This single-goroutine memory map demonstrates deduplication only. Production deduplication must commit the event identity and business effect atomically; otherwise a crash can lose work or repeat the effect.","title":"How to read this example"}],"takeaway":"Repeating a message does not repeat its business effect. Buffering can isolate timing, but it does not guarantee business completion. Define dead-letter handling, retry limits and observability. A transactional outbox can bridge a database commit and later publication; a plain goroutine cannot replace durable messaging.","title":"Event-driven services: delivery and idempotency","unitID":"architecture","wrongAnswers":["A goroutine guarantees durable delivery","Every event is delivered exactly once automatically"]},{"conceptTag":"architecture.microservices","designGuide":{"cautions":["Network and data consistency costs are ongoing","Shared releases can create a distributed monolith"],"cost":"Very high","family":"Architecture","flow":["Caller sets a deadline","Remote service owns its contract and data","Caller handles a partial failure"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":2},{"scenario":"Independent distributed services","score":5}],"strengths":["Teams need independent deployment and isolation","A capability has distinct scaling requirements"]},"hint":"The dependency contract distinguishes a business answer from a failed lookup.","id":"architecture.microservices","introduction":"Extract a remote boundary only when its independence is valuable. A microservice owns a business capability, its data and its deployment. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Independent ownership helps teams with different release and scaling needs.","objective":"Extract a remote boundary only when its independence is valuable.","question":"Which statement best describes Microservices: pay for independent ownership?","references":["https://martinfowler.com/articles/microservice-trade-offs.html","https://pkg.go.dev/context","https://go.dev/doc/modules/layout"],"reviewAnswer":"Adds independent ownership and partial remote failures","reviewPrompt":"Microservice boundary","sections":[{"body":"A microservice owns a business capability, its data and its deployment. A Go package boundary is cheap; a service boundary adds timeouts, partial failures and contract evolution. Splitting one synchronous call chain into many processes can create a distributed monolith.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Inventory interface {\n\tAvailable(context.Context, string) (bool, error)\n}\ntype OfflineInventory struct{}\n\nfunc (OfflineInventory) Available(ctx context.Context, id string) (bool, error) {\n\treturn false, errors.New(\"inventory unavailable\")\n}\nfunc CanShip(ctx context.Context, inventory Inventory, id string) error {\n\tok, err := inventory.Available(ctx, id)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"check inventory: %w\", err)\n\t}\n\tif !ok {\n\t\treturn errors.New(\"out of stock\")\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tfmt.Println(CanShip(context.Background(), OfflineInventory{}, \"book\"))\n}\n\n// Output:\n// check inventory: inventory unavailable\n","language":"go","title":"A complete Go example","walkthrough":"The dependency contract distinguishes a business answer from a failed lookup. The fake models a remote failure deterministically without opening a socket. A real adapter must add deadlines, authentication and response validation rather than treating failure as zero stock."},{"body":"Independent ownership helps teams with different release and scaling needs. It also requires tracing, deployment automation and data consistency design. Start with a modular monolith when one team can operate it; high request volume alone is not a service-count target.","title":"Tradeoffs and the simpler alternative"},{"body":"A service owns a capability, its durable data and an operational responsibility. Sharing one database schema across independently deployed services often preserves tight coupling while adding network failures. Define the public API or event contract and the team that can evolve it. Prefer coarse business boundaries over a service per table. A modular monolith is a useful starting point when the same small team owns all capabilities and coordinated releases are acceptable.","title":"Draw ownership and data boundaries first"},{"body":"A request may time out after the remote effect succeeds. Bound the total deadline, propagate cancellation, make retryable mutations idempotent and avoid retries at every layer. Keep cross-service transactions out of local transaction assumptions: model pending work, reconciliation or compensations explicitly. A circuit breaker can protect a struggling dependency but does not correct invalid data or guarantee delivery. Separate authentication from service authorization and protect both transport and business operations.","title":"Budget for partial failure"},{"body":"Choose one capability whose independent scaling, release cadence or fault isolation is measured to matter. Put an adapter behind its current contract, move ownership deliberately and define the migration source of truth. Shadow read traffic can compare results without duplicating mutations. Test backward-compatible API changes before rolling out producers and consumers separately. Observability, deploy automation, secrets, on-call and recovery are part of the design cost, not optional work after the code has been split.","title":"Plan extraction and rollback"},{"body":"Independent ownership helps teams with different release and scaling needs. It also requires tracing, deployment automation and data consistency design. Start with a modular monolith when one team can operate it; high request volume alone is not a service-count target.","title":"Practical limits and cautions"},{"body":"The dependency contract distinguishes a business answer from a failed lookup. The fake models a remote failure deterministically without opening a socket. A real adapter must add deadlines, authentication and response validation rather than treating failure as zero stock.","title":"How to read this example"}],"takeaway":"Adds independent ownership and partial remote failures. Independent ownership helps teams with different release and scaling needs. It also requires tracing, deployment automation and data consistency design. Start with a modular monolith when one team can operate it; high request volume alone is not a service-count target.","title":"Microservices: pay for independent ownership","unitID":"architecture","wrongAnswers":["A package rename provides deployment independence","A failed lookup is always equivalent to zero stock"]},{"conceptTag":"architecture.soa","designGuide":{"cautions":["Shared contracts need compatibility management","Centralized orchestration can become a bottleneck"],"cost":"High","family":"Architecture","flow":["Consumer sends a defined request","Service enforces its contract","Consumer interprets a defined result"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":4}],"strengths":["Existing systems need explicit integration boundaries","Capabilities are reused across several applications"]},"hint":"The request and response encode units in field names.","id":"architecture.soa","introduction":"Compare service-oriented integration with smaller independently owned services. Service-oriented architecture organizes reusable business capabilities behind contracts, often across existing enterprise systems. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Broad shared services can reduce integration duplication but become release bottlenecks.","objective":"Compare service-oriented integration with smaller independently owned services.","question":"Which statement best describes SOA and RPC: stable service contracts?","references":["https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/microservices","https://grpc.io/docs/what-is-grpc/core-concepts/","https://go.dev/doc/modules/layout"],"reviewAnswer":"Defines units, outcomes and compatibility at a boundary","reviewPrompt":"Service contract","sections":[{"body":"Service-oriented architecture organizes reusable business capabilities behind contracts, often across existing enterprise systems. Neither SOA nor RPC requires a particular protocol. A contract needs explicit units, failure semantics and version rules regardless of JSON or generated stubs.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype QuoteRequest struct{ WeightGrams int }\ntype QuoteResponse struct{ PriceCents int }\n\nfunc Quote(req QuoteRequest) (QuoteResponse, error) {\n\tif req.WeightGrams <= 0 {\n\t\treturn QuoteResponse{}, errors.New(\"weight required\")\n\t}\n\treturn QuoteResponse{PriceCents: 500 + req.WeightGrams/10}, nil\n}\n\nfunc main() {\n\tresult, err := Quote(QuoteRequest{WeightGrams: 200})\n\tfmt.Println(result.PriceCents, err)\n}\n\n// Output:\n// 520 <nil>\n","language":"go","title":"A complete Go example","walkthrough":"The request and response encode units in field names. The example uses a local function so the contract is visible without transport code. An RPC adapter would still need to distinguish validation errors, deadline expiry and unavailable dependencies."},{"body":"Broad shared services can reduce integration duplication but become release bottlenecks. Avoid a universal service that owns every domain. Microservices emphasize independent capability ownership; SOA is a broader service integration approach, so real systems can share ideas from both.","title":"Tradeoffs and the simpler alternative"},{"body":"An RPC method should express a stable business operation rather than expose a database row shape. Define identifiers, validation, cancellation and error categories, along with message evolution rules. Adding an optional field may be compatible while changing its meaning is not. Keep generated transport types at the adapter boundary if their evolution should not dictate the domain model. An interface in Go is a local language contract; it does not automatically provide a versioned remote protocol.","title":"Design an API contract for independent clients"},{"body":"If a client times out on Reserve, it may not know whether a reservation exists. A stable operation ID allows retry or status lookup without repeating the effect. Set one deadline and distinguish validation failure, denied access, missing resource and transient service failure. Avoid returning unbounded result lists; pagination and resource budgets belong in the contract. Streaming APIs also need backpressure and a shutdown policy.","title":"Make timeout ambiguity explicit"},{"body":"Run contract fixtures against old and new request shapes. Test that a server accepting a new field still handles older callers, and that clients tolerate allowed unknown fields according to the protocol. Record latency and error rate per operation without logging credentials or whole sensitive payloads. RPC or service-oriented integration can centralize a genuine shared capability, but a synchronous dependency on many services can become a distributed call chain with poor availability.","title":"Verify mixed-version deployment"},{"body":"Broad shared services can reduce integration duplication but become release bottlenecks. Avoid a universal service that owns every domain. Microservices emphasize independent capability ownership; SOA is a broader service integration approach, so real systems can share ideas from both.","title":"Practical limits and cautions"},{"body":"The request and response encode units in field names. The example uses a local function so the contract is visible without transport code. An RPC adapter would still need to distinguish validation errors, deadline expiry and unavailable dependencies.","title":"How to read this example"}],"takeaway":"Defines units, outcomes and compatibility at a boundary. Broad shared services can reduce integration duplication but become release bottlenecks. Avoid a universal service that owns every domain. Microservices emphasize independent capability ownership; SOA is a broader service integration approach, so real systems can share ideas from both.","title":"SOA and RPC: stable service contracts","unitID":"architecture","wrongAnswers":["A protocol makes failures disappear","One shared service must own every business domain"]},{"conceptTag":"architecture.bff","designGuide":{"cautions":["Adds a deployed component and timeout budget","Duplicated business rules can diverge"],"cost":"High","family":"Architecture","flow":["Mobile requests a home view","BFF composes safe client fields","Domain services retain business rules"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":4}],"strengths":["Mobile and desktop have different data needs","Aggregation avoids many client round trips"]},"hint":"Home maps a rich internal object to the client view without copying InternalNote. In a real BFF, downstream calls can fail independently; define timeout budgets and whether partial data is acceptable before parallelizing aggregation.","id":"architecture.bff","introduction":"Compose client-specific views while retaining business ownership. A backend for frontend provides an API suited to a particular client, such as mobile. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"One extra boundary helps clients with genuinely different data and release needs.","objective":"Compose client-specific views while retaining business ownership.","question":"Which statement best describes BFF: an API shaped for one client?","references":["https://learn.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends","https://go.dev/doc/modules/layout"],"reviewAnswer":"Shapes an API around one client’s needs","reviewPrompt":"Backend for frontend","sections":[{"body":"A backend for frontend provides an API suited to a particular client, such as mobile. It can combine downstream responses and remove fields the client does not need. Authorization and business invariants still belong at trustworthy service boundaries, not only in the BFF.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Profile struct{ Name, InternalNote string }\ntype MobileHome struct {\n\tGreeting string\n\tUnread   int\n}\n\nfunc Home(p Profile, unread int) MobileHome {\n\treturn MobileHome{Greeting: \"Hello, \" + p.Name, Unread: unread}\n}\n\nfunc main() {\n\tview := Home(Profile{Name: \"Ada\", InternalNote: \"private\"}, 3)\n\tfmt.Println(view.Greeting, view.Unread)\n}\n\n// Output:\n// Hello, Ada 3\n","language":"go","title":"A complete Go example","walkthrough":"Home maps a rich internal object to the client view without copying InternalNote. In a real BFF, downstream calls can fail independently; define timeout budgets and whether partial data is acceptable before parallelizing aggregation."},{"body":"One extra boundary helps clients with genuinely different data and release needs. If all clients need the same API, a shared endpoint may be simpler. Do not duplicate pricing or authorization policy in every BFF; client shaping is its main reason to change.","title":"Tradeoffs and the simpler alternative"},{"body":"A backend for frontend adapts several capabilities to the screens of a specific client. It can reduce round trips, tailor pagination and hide service topology. Keep pricing, payment and authorization invariants in the owning service; a BFF should not become a second business system with conflicting rules. A mobile BFF and a web BFF can differ in response shape while using the same underlying contracts.","title":"Aggregate for one client without moving domain ownership"},{"body":"Call independent services concurrently under a total deadline, cap concurrency and decide which results are essential. A profile panel might allow a missing optional recommendation, while a checkout must fail if price validation is unavailable. Preserve the distinction in the response instead of returning an empty success object for every dependency failure. Cache only with a key that includes required user and permission scope; shared caching of personalized responses can leak data.","title":"Handle fan-out without multiplying latency"},{"body":"Use fixtures for complete results, one optional dependency timeout and one essential dependency failure. Verify authorization on the aggregate response and prevent internal service errors from exposing private topology. Track fan-out count and deadline exhaustion. Introduce a BFF when distinct clients actually need different composition; one frontend calling one simple API rarely needs another deployable intermediary.","title":"Test screen contracts and graceful degradation"},{"body":"One extra boundary helps clients with genuinely different data and release needs. If all clients need the same API, a shared endpoint may be simpler. Do not duplicate pricing or authorization policy in every BFF; client shaping is its main reason to change.","title":"Practical limits and cautions"}],"takeaway":"Shapes an API around one client’s needs. One extra boundary helps clients with genuinely different data and release needs. If all clients need the same API, a shared endpoint may be simpler. Do not duplicate pricing or authorization policy in every BFF; client shaping is its main reason to change.","title":"BFF: an API shaped for one client","unitID":"architecture","wrongAnswers":["Owns every downstream business invariant","Requires a BFF for every screen"]},{"conceptTag":"architecture.serverless","designGuide":{"cautions":["Invocation limits and cold starts affect design","Retries require idempotent durable effects"],"cost":"Medium to high","family":"Architecture","flow":["Platform supplies an invocation","Pure handler validates and computes","Adapter writes the response or durable effect"],"ratings":[{"scenario":"Small tool or CLI","score":1},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":4}],"strengths":["Tasks are bounded and traffic varies","Managed invocation scaling is valuable"]},"hint":"Handle is pure application behavior, independent of a provider SDK. An outer adapter decodes the event and serializes the result. Moving a side effect into this function would require an idempotency policy, not a process-global seen map.","id":"architecture.serverless","introduction":"Separate invocation mechanics from deterministic application behavior. A function platform manages execution capacity while your handler processes an invocation. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Functions suit bounded event-driven tasks and variable workloads.","objective":"Separate invocation mechanics from deterministic application behavior.","question":"Which statement best describes Serverless handlers: bounded work and retry-safe effects?","references":["https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html","https://go.dev/doc/modules/layout"],"reviewAnswer":"Processes bounded invocations with external durable state","reviewPrompt":"Serverless handler","sections":[{"body":"A function platform manages execution capacity while your handler processes an invocation. Keep durable state outside the process and assume a retry policy may invoke the same logical work again. Provider limits, cold starts and event semantics belong in the design.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Event struct{ Name string }\n\nfunc Handle(e Event) (string, error) {\n\tname := strings.TrimSpace(e.Name)\n\tif name == \"\" {\n\t\treturn \"\", errors.New(\"name required\")\n\t}\n\treturn \"Hello, \" + name, nil\n}\n\nfunc main() {\n\tmessage, err := Handle(Event{Name: \" Ada \"})\n\tfmt.Println(message, err)\n}\n\n// Output:\n// Hello, Ada <nil>\n","language":"go","title":"A complete Go example","walkthrough":"Handle is pure application behavior, independent of a provider SDK. An outer adapter decodes the event and serializes the result. Moving a side effect into this function would require an idempotency policy, not a process-global seen map."},{"body":"Functions suit bounded event-driven tasks and variable workloads. Long-running connections or strict latency targets may favor a continuously running service. Check the chosen platform’s actual Go runtime, resource limits and billing; serverless does not mean operations-free.","title":"Tradeoffs and the simpler alternative"},{"body":"Treat process memory as a disposable cache, not the authoritative record of a completed job. Reused instances may retain state between calls while new instances begin empty. Validate input and obtain a durable idempotency key for retried operations. Bound execution time, payload size and concurrency. A serverless function is a deployment unit; the same clean application service can also run in an ordinary HTTP server.","title":"Keep a handler independent of a warm process"},{"body":"A queue-triggered handler may be invoked again after a timeout or lost acknowledgement. Persist progress and use the external provider idempotency mechanism when available. A local done map does not survive another instance. If an effect succeeds but recording success fails, the retry must reconcile rather than blindly repeat. Connection pools and downstream database capacity need limits because rapid function scaling can overwhelm a shared dependency.","title":"Design retry-safe external effects"},{"body":"Observe cold and warm latency, failures, throttling, queue age and per-invocation cost. Test execution with no warmed globals and interrupted work, not only by calling the function twice inside one test process. Use serverless for bounded independently triggered work where its scaling and operations model fits. Long-lived connections, latency-sensitive steady load or complex coordination may be simpler in a service or worker.","title":"Measure the real operational fit"},{"body":"Functions suit bounded event-driven tasks and variable workloads. Long-running connections or strict latency targets may favor a continuously running service. Check the chosen platform’s actual Go runtime, resource limits and billing; serverless does not mean operations-free.","title":"Practical limits and cautions"}],"takeaway":"Processes bounded invocations with external durable state. Functions suit bounded event-driven tasks and variable workloads. Long-running connections or strict latency targets may favor a continuously running service. Check the chosen platform’s actual Go runtime, resource limits and billing; serverless does not mean operations-free.","title":"Serverless handlers: bounded work and retry-safe effects","unitID":"architecture","wrongAnswers":["Process globals are durable across retries","The platform removes all operational decisions"]},{"conceptTag":"architecture.pipes-filters","designGuide":{"cautions":["Stage order and error propagation need a contract","Concurrency adds cancellation and backpressure work"],"cost":"Medium","family":"Architecture","flow":["Decode or normalize","Validate and transform","Encode or emit"],"ratings":[{"scenario":"Small tool or CLI","score":5},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["A data flow has independently testable stages","Streaming can reduce whole-input memory use"]},"hint":"The pipeline first trims and then capitalizes, so order matters.","id":"architecture.pipes-filters","introduction":"Compose transformations while making backpressure and errors explicit. A pipes-and-filters design passes data through small stages such as decode, validate and transform. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use stages when transformations compose naturally and need separate tests.","objective":"Compose transformations while making backpressure and errors explicit.","question":"Which statement best describes Pipes and filters: data through independent stages?","references":["https://go.dev/blog/pipelines","https://go.dev/doc/modules/layout"],"reviewAnswer":"Composes ordered transformations with explicit handoffs","reviewPrompt":"Pipes and filters","sections":[{"body":"A pipes-and-filters design passes data through small stages such as decode, validate and transform. Stages can be ordinary functions before concurrency is needed. Streaming changes the memory budget; concurrent stages also need cancellation and a bounded handoff.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Stage func(string) string\n\nfunc Pipeline(input string, stages ...Stage) string {\n\tfor _, stage := range stages {\n\t\tinput = stage(input)\n\t}\n\treturn input\n}\n\nfunc main() {\n\tresult := Pipeline(\"  go  \", strings.TrimSpace, strings.ToUpper)\n\tfmt.Println(result)\n}\n\n// Output:\n// GO\n","language":"go","title":"A complete Go example","walkthrough":"The pipeline first trims and then capitalizes, so order matters. Function values make each stage independently reusable. This synchronous version avoids goroutine management; later streaming versions can preserve the same stage boundaries with explicit error propagation."},{"body":"Use stages when transformations compose naturally and need separate tests. Shared state between stages undermines isolation. A single expression is simpler for one trivial transformation, and unbounded channel buffers do not solve a slow downstream consumer.","title":"Tradeoffs and the simpler alternative"},{"body":"A stage consumes one representation and produces another: parse, normalize, validate and summarize. Start with ordinary function composition for finite in-memory data. Introduce channels only when streaming or independent work justifies coordination. Every stage needs a policy for malformed input, cancellation and output ownership. An unbounded buffer can turn temporary downstream slowness into a memory failure.","title":"Define stage contracts and resource bounds"},{"body":"If a downstream consumer exits early, upstream producers must be able to stop rather than block forever on send. Pass context, select on cancellation where sends can block, and let the owner of a channel close it after all producers finish. Multiple concurrent stages may reorder results; preserve an input index if order is required. A goroutine per item is not a bounded worker pool.","title":"Propagate cancellation through the whole pipeline"},{"body":"Verify a stage with empty input, invalid input, a slow consumer and cancellation halfway through. Check that completion waits for owned goroutines and that no sender is left writing to a closed channel. Benchmark representative data before adding concurrency: parsing small records in separate goroutines can cost more than a loop. Pipes and filters suit stream transformations; they are less helpful when each stage requires shared mutable domain state and distributed transactions.","title":"Test pressure as well as transformation"},{"body":"Use stages when transformations compose naturally and need separate tests. Shared state between stages undermines isolation. A single expression is simpler for one trivial transformation, and unbounded channel buffers do not solve a slow downstream consumer.","title":"Practical limits and cautions"},{"body":"The pipeline first trims and then capitalizes, so order matters. Function values make each stage independently reusable. This synchronous version avoids goroutine management; later streaming versions can preserve the same stage boundaries with explicit error propagation.","title":"How to read this example"}],"takeaway":"Composes ordered transformations with explicit handoffs. Use stages when transformations compose naturally and need separate tests. Shared state between stages undermines isolation. A single expression is simpler for one trivial transformation, and unbounded channel buffers do not solve a slow downstream consumer.","title":"Pipes and filters: data through independent stages","unitID":"architecture","wrongAnswers":["Stages may be reordered without checking semantics","More goroutines always improve throughput"]},{"conceptTag":"architecture.microkernel","designGuide":{"cautions":["Contract evolution affects all extensions","In-process extensions share the core’s failure domain"],"cost":"High","family":"Architecture","flow":["Core defines an extension contract","Startup registers an implementation","Core invokes selected behavior"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["A product supports optional capabilities","Extensions can follow a stable small contract"]},"hint":"The core dispatches through a function contract, and the startup map explicitly selects available behavior.","id":"architecture.microkernel","introduction":"Extend behavior through contracts without assuming dynamic shared libraries. A microkernel or plugin architecture keeps a stable core and accepts extensions through a narrow contract. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Extensions in the same process can panic, block or access shared resources; an interface is not a security sandbox.","objective":"Extend behavior through contracts without assuming dynamic shared libraries.","question":"Which statement best describes Microkernel: a small core with explicit extensions?","references":["https://pkg.go.dev/plugin","https://go.dev/doc/modules/layout"],"reviewAnswer":"Lets a small core invoke explicitly registered behavior","reviewPrompt":"Extension contract","sections":[{"body":"A microkernel or plugin architecture keeps a stable core and accepts extensions through a narrow contract. Go can register ordinary functions at startup. This is different from loading shared objects with package plugin, which has platform and build compatibility constraints.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Transform func(string) string\ntype Core struct{ extensions map[string]Transform }\n\nfunc (c Core) Apply(name, input string) (string, bool) {\n\tf, ok := c.extensions[name]\n\tif !ok {\n\t\treturn \"\", false\n\t}\n\treturn f(input), true\n}\n\nfunc main() {\n\tcore := Core{extensions: map[string]Transform{\"upper\": strings.ToUpper}}\n\tout, ok := core.Apply(\"upper\", \"go\")\n\tfmt.Println(out, ok)\n}\n\n// Output:\n// GO true\n","language":"go","title":"A complete Go example","walkthrough":"The core dispatches through a function contract, and the startup map explicitly selects available behavior. This static registry needs no runtime code loading. Validate duplicate names and extension capabilities when building a larger registry."},{"body":"Extensions in the same process can panic, block or access shared resources; an interface is not a security sandbox. Use subprocess or RPC isolation for untrusted extensions. Native plugin loading is not supported by GopherForge’s WASI runtime.","title":"Tradeoffs and the simpler alternative"},{"body":"The core owns stable policy and chooses extensions through a small interface or registry. An extension may format, validate or dispatch one capability. Register it explicitly at startup so dependencies and failure are visible. Compile-time implementations and process-isolated extensions are different operational models. Do not assume Go binary plugins are portable across all systems or supported inside the iOS sandbox; the lesson example uses ordinary linked Go values.","title":"Keep the extension contract narrower than the core"},{"body":"Decide when an extension initializes, whether requests may run concurrently, who closes resources and what happens if initialization fails. A panic in an in-process extension can affect the host; an interface does not create isolation. Untrusted extensions require a real sandbox or process boundary with permissions and time budgets. Version the contract when independently delivered extensions need compatibility checks.","title":"Define lifecycle and failure containment"},{"body":"Test extensions against a shared contract, including invalid configuration and cleanup. Prefer one small extension point justified by a real variation over a generic object bag with string keys and reflection. A registry of two ordinary functions may be enough. A microkernel pays off when third-party or product-specific variation evolves independently; if every extension changes with the core, a direct function call is often easier to understand.","title":"Resist a universal extension API"},{"body":"Extensions in the same process can panic, block or access shared resources; an interface is not a security sandbox. Use subprocess or RPC isolation for untrusted extensions. Native plugin loading is not supported by GopherForge’s WASI runtime.","title":"Practical limits and cautions"},{"body":"The core dispatches through a function contract, and the startup map explicitly selects available behavior. This static registry needs no runtime code loading. Validate duplicate names and extension capabilities when building a larger registry.","title":"How to read this example"}],"takeaway":"Lets a small core invoke explicitly registered behavior. Extensions in the same process can panic, block or access shared resources; an interface is not a security sandbox. Use subprocess or RPC isolation for untrusted extensions. Native plugin loading is not supported by GopherForge’s WASI runtime.","title":"Microkernel: a small core with explicit extensions","unitID":"architecture","wrongAnswers":["An interface safely sandboxes untrusted code","Go plugins work identically on every platform"]},{"conceptTag":"architecture.web-queue-worker","designGuide":{"cautions":["Acceptance and completion need separate status","Leases, retries and duplicates require durable design"],"cost":"High","family":"Architecture","flow":["HTTP accepts and durably records a job","Queue leases or delivers the job","Worker commits an idempotent result"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":5}],"strengths":["Slow work should not hold an HTTP request","Workers need independent throughput control"]},"hint":"The example exposes acceptance and later consumption as different operations.","id":"architecture.web-queue-worker","introduction":"Separate request latency from background completion. A web-queue-worker system accepts a task, durably records it and lets a worker finish later. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use a durable queue and idempotent worker for valuable work.","objective":"Separate request latency from background completion.","question":"Which statement best describes Web, queue, worker: make slow work durable?","references":["https://learn.microsoft.com/en-us/azure/architecture/guide/architecture-styles/web-queue-worker","https://go.dev/doc/modules/layout"],"reviewAnswer":"Separates acceptance from eventual job completion","reviewPrompt":"Durable background work","sections":[{"body":"A web-queue-worker system accepts a task, durably records it and lets a worker finish later. The response should distinguish accepted from completed. Job identities and status transitions let clients safely retry and observe progress without keeping an HTTP request open.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Queue struct{ jobs []string }\n\nfunc (q *Queue) Accept(id string) error {\n\tif id == \"\" {\n\t\treturn errors.New(\"job id required\")\n\t}\n\tq.jobs = append(q.jobs, id)\n\treturn nil\n}\nfunc (q *Queue) Next() (string, bool) {\n\tif len(q.jobs) == 0 {\n\t\treturn \"\", false\n\t}\n\tid := q.jobs[0]\n\tq.jobs = q.jobs[1:]\n\treturn id, true\n}\n\nfunc main() {\n\tq := &Queue{}\n\tfmt.Println(q.Accept(\"report-1\"))\n\tid, ok := q.Next()\n\tfmt.Println(id, ok)\n}\n\n// Output:\n// <nil>\n// report-1 true\n","language":"go","title":"A complete Go example","walkthrough":"The example exposes acceptance and later consumption as different operations. Its slice is a single-process teaching queue: a crash loses jobs and Next removes them before work completes. A durable broker needs acknowledgments or leases and redelivery handling."},{"body":"Use a durable queue and idempotent worker for valuable work. Record status and propagate trace identifiers so accepted jobs do not disappear operationally. A goroutine can handle disposable local work, but cannot promise completion after the process exits.","title":"Tradeoffs and the simpler alternative"},{"body":"An HTTP 202 response says work was accepted, not completed. Validate and authorize the request, allocate a job ID and persist the job before returning success. Expose a status endpoint with pending, running, succeeded and failed states. Put the relevant input or an immutable reference in durable storage. A channel living inside the web process loses queued work when that process exits.","title":"Make accepting work a durable promise"},{"body":"A worker claims a job for a limited lease and renews it while progressing. If it crashes, another worker can reclaim after expiry. Both may briefly believe they own the same job during a partition, so use an ownership token or fencing where the effect requires it. Bound attempts and preserve diagnostic state for exhausted jobs. A retry should resume or reconcile a durable operation rather than issue the same non-idempotent external effect twice.","title":"Use leases, retries and idempotent work"},{"body":"Monitor oldest pending age, queue depth, active leases, completion latency and exhausted retries. Test a crash after the effect but before status update, cancellation while waiting, and a worker that loses its lease. Use an outbox when job creation and an application state change must commit together. Separate web and worker deployment only when resource or scaling needs justify it; they can initially share one executable and a durable queue.","title":"Operate and test the backlog"},{"body":"Use a durable queue and idempotent worker for valuable work. Record status and propagate trace identifiers so accepted jobs do not disappear operationally. A goroutine can handle disposable local work, but cannot promise completion after the process exits.","title":"Practical limits and cautions"},{"body":"The example exposes acceptance and later consumption as different operations. Its slice is a single-process teaching queue: a crash loses jobs and Next removes them before work completes. A durable broker needs acknowledgments or leases and redelivery handling.","title":"How to read this example"}],"takeaway":"Separates acceptance from eventual job completion. Use a durable queue and idempotent worker for valuable work. Record status and propagate trace identifiers so accepted jobs do not disappear operationally. A goroutine can handle disposable local work, but cannot promise completion after the process exits.","title":"Web, queue, worker: make slow work durable","unitID":"architecture","wrongAnswers":["An HTTP accepted response proves the job finished","An in-memory slice survives process failure"]},{"conceptTag":"clean.names","designGuide":{"cautions":["Verbosity can hide a simple idea","Naming cannot fix mixed responsibilities"],"cost":"Low","family":"Clean Go","flow":["Caller reads the contract","Typed input exposes units","Result makes the decision explicit"],"ratings":[],"strengths":["Different units or meanings can be confused","An API is read outside its implementation"]},"hint":"Delay has a duration type rather than an undocumented integer unit.","id":"clean.names","introduction":"Make a caller understand units, results and ownership from the API. Names should reduce guesses at the call site. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Choose brevity in small scopes and precision at boundaries.","objective":"Make a caller understand units, results and ownership from the API.","question":"Which statement best describes Names that expose responsibility?","references":["https://go.dev/blog/package-names","https://pkg.go.dev/time","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Reduce ambiguity with types and precise API names","reviewPrompt":"Explicit units","sections":[{"body":"Names should reduce guesses at the call site. Include units when a number otherwise has several meanings, avoid repeating the package name in every exported identifier, and replace vague helpers with a responsibility such as parsing a duration or calculating a quote.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\ntype RetryPolicy struct {\n\tDelay       time.Duration\n\tMaxAttempts int\n}\n\nfunc NextDelay(policy RetryPolicy, attempt int) (time.Duration, bool) {\n\tif attempt >= policy.MaxAttempts {\n\t\treturn 0, false\n\t}\n\treturn policy.Delay, true\n}\n\nfunc main() {\n\tdelay, retry := NextDelay(RetryPolicy{Delay: 250 * time.Millisecond, MaxAttempts: 3}, 1)\n\tfmt.Println(delay, retry)\n}\n\n// Output:\n// 250ms true\n","language":"go","title":"A complete Go example","walkthrough":"Delay has a duration type rather than an undocumented integer unit. NextDelay returns both a value and a decision, so zero is not overloaded to mean stop. Attempt numbering must still be documented: this example uses a zero-based attempt index."},{"body":"Choose brevity in small scopes and precision at boundaries. A long name cannot repair a confused responsibility. Keep comments for contracts, assumptions and reasons; let gofmt handle alignment rather than preserving a personal formatting convention.","title":"Tradeoffs and the simpler alternative"},{"body":"Prefer ReserveStock to Process and OrderID to a bare string whose meaning changes by call site. Include units when a numeric type does not make them clear; use time.Duration rather than an undocumented integer timeout. A name should tell the caller whether a method mutates, blocks or acquires a resource. Avoid repeating a package name in every exported identifier when the qualified call already supplies it. Short names remain useful for small, obvious scopes such as a loop index.","title":"Name the contract, not the implementation accident"},{"body":"A named type can distinguish CustomerID from OrderID at compile time, but a string alias alone does not validate content. Validate input at the boundary and construct a value that has a documented invariant. Avoid boolean flag arguments whose call-site meaning is unclear; separate operations or a small options type can be easier to read. Do not replace every primitive with a wrapper: choose types where confusing two values or forgetting validation has a real cost.","title":"Make invalid states harder to pass"},{"body":"Read a call without opening its implementation. Can you tell whether the result may be partial, who owns returned bytes and which error means missing? Rename or document the contract when the answer is unclear. Test a malformed ID and an empty value before claiming a constructor makes invalid states impossible. During a rename, keep public compatibility or provide a migration path; internal clarity and external API stability are separate concerns.","title":"Review names with a caller and a failure"},{"body":"Choose brevity in small scopes and precision at boundaries. A long name cannot repair a confused responsibility. Keep comments for contracts, assumptions and reasons; let gofmt handle alignment rather than preserving a personal formatting convention.","title":"Practical limits and cautions"},{"body":"Delay has a duration type rather than an undocumented integer unit. NextDelay returns both a value and a decision, so zero is not overloaded to mean stop. Attempt numbering must still be documented: this example uses a zero-based attempt index.","title":"How to read this example"}],"takeaway":"Reduce ambiguity with types and precise API names. Choose brevity in small scopes and precision at boundaries. A long name cannot repair a confused responsibility. Keep comments for contracts, assumptions and reasons; let gofmt handle alignment rather than preserving a personal formatting convention.","title":"Names that expose responsibility","unitID":"clean-code","wrongAnswers":["Long names guarantee a useful abstraction","Every integer should mean milliseconds implicitly"]},{"conceptTag":"clean.interfaces","designGuide":{"cautions":["Wide interfaces couple unrelated behavior","An interface containing a nil pointer is not nil"],"cost":"Low","family":"Clean Go","flow":["Consumer asks for Read","Concrete reader satisfies the contract","Consumer handles value and error"],"ratings":[],"strengths":["A boundary needs substitution","Tests can use small deterministic implementations"]},"hint":"FirstByte accepts only the Read behavior that io.ReadFull needs, so a string reader works without an inheritance relationship. The error still belongs to the result: an empty reader would return EOF, not a valid zero byte.","id":"clean.interfaces","introduction":"Describe a real substitution boundary without wrapping every concrete type. A consumer knows which behavior it needs. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Do not define a giant interface beside an implementation merely to mock it.","objective":"Describe a real substitution boundary without wrapping every concrete type.","question":"Which statement best describes Small interfaces belong near the consumer?","references":["https://go.dev/wiki/CodeReviewComments#interfaces","https://pkg.go.dev/io#ReadFull","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"States the behavior needed by its caller","reviewPrompt":"Consumer interface","sections":[{"body":"A consumer knows which behavior it needs. Define a small interface there and let concrete implementations satisfy it implicitly. Returning a concrete type often gives callers a clearer API; an interface becomes useful when a caller needs substitution, testing or multiple implementations.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\nfunc FirstByte(r io.Reader) (byte, error) {\n\tvar b [1]byte\n\t_, err := io.ReadFull(r, b[:])\n\treturn b[0], err\n}\n\nfunc main() {\n\tb, err := FirstByte(strings.NewReader(\"Go\"))\n\tfmt.Printf(\"%c %v\\n\", b, err)\n}\n\n// Output:\n// G <nil>\n","language":"go","title":"A complete Go example","walkthrough":"FirstByte accepts only the Read behavior that io.ReadFull needs, so a string reader works without an inheritance relationship. The error still belongs to the result: an empty reader would return EOF, not a valid zero byte."},{"body":"Do not define a giant interface beside an implementation merely to mock it. Avoid typed nil pointers inside interface results, and test empty input as well as the successful path. For a local helper with one implementation, a concrete parameter may be clearer.","title":"Tradeoffs and the simpler alternative"},{"body":"A handler needing Get(ctx, id) does not need a repository interface with twenty unrelated methods. Define the interface near that handler or application service, and let the concrete store satisfy it implicitly. This avoids coupling clients to methods they never call. Return concrete implementations from constructors unless an abstraction is useful to the caller. Accepting an interface is not inherently better when a function simply needs a byte slice or one callback.","title":"Let the consumer choose the minimum capability"},{"body":"The type system checks signatures, not semantics. State whether a missing record is an error, whether results alias internal data, whether the value is concurrency-safe, and whether cancellation can interrupt IO. A typed nil pointer stored in an interface is not a nil interface; avoid returning it as a successful dependency. Tests should verify the same contract for fake and real implementations rather than treating a fake as proof that storage behaves correctly.","title":"Document behavior that method sets cannot express"},{"body":"Clock, payment and durable storage boundaries often benefit from a small substitute in a test. A pure arithmetic helper rarely needs its own interface. Keep a compile-time implementation check near an adapter when it helps detect drift, and exercise the adapter contract as well. If every interface has exactly one consumer-independent clone of a large concrete method set, reconsider whether the abstraction is protecting a real boundary or only adding navigation.","title":"Introduce substitution where change is real"},{"body":"Do not define a giant interface beside an implementation merely to mock it. Avoid typed nil pointers inside interface results, and test empty input as well as the successful path. For a local helper with one implementation, a concrete parameter may be clearer.","title":"Practical limits and cautions"}],"takeaway":"States the behavior needed by its caller. Do not define a giant interface beside an implementation merely to mock it. Avoid typed nil pointers inside interface results, and test empty input as well as the successful path. For a local helper with one implementation, a concrete parameter may be clearer.","title":"Small interfaces belong near the consumer","unitID":"clean-code","wrongAnswers":["Must mirror every method of the concrete type","Requires explicit implements declarations"]},{"conceptTag":"clean.errors","designGuide":{"cautions":["Wrapping can expose implementation contracts","Sensitive fields do not belong in errors"],"cost":"Low","family":"Clean Go","flow":["Dependency returns a cause","Application adds operation context","Boundary classifies and reports once"],"ratings":[],"strengths":["Callers need failure classification","Operations need useful diagnostic context"]},"hint":"Wrapping preserves ErrMissing for errors.Is while adding the project operation for a human. The program prints once at the boundary. Replacing %w with %v would keep the message but lose this cause chain.","id":"clean.errors","introduction":"Keep failure context useful without logging the same failure at every layer. An error value travels to the layer that can decide what to do: retry, map to a response or stop. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Expose stable error categories only when they are part of the package contract.","objective":"Keep failure context useful without logging the same failure at every layer.","question":"Which statement best describes Errors: preserve cause and choose one reporting boundary?","references":["https://go.dev/blog/go1.13-errors","https://pkg.go.dev/errors","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Adds context while preserving a cause for errors.Is","reviewPrompt":"Error wrapping","sections":[{"body":"An error value travels to the layer that can decide what to do: retry, map to a response or stop. Wrap a cause when callers need classification. Return enough context to locate the operation, but avoid adding secrets or logging the same failure as it moves upward.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar ErrMissing = errors.New(\"missing project\")\n\nfunc Load(id string) error { return fmt.Errorf(\"load %s: %w\", id, ErrMissing) }\n\nfunc main() {\n\terr := Load(\"p1\")\n\tfmt.Println(errors.Is(err, ErrMissing))\n\tfmt.Println(err)\n}\n\n// Output:\n// true\n// load p1: missing project\n","language":"go","title":"A complete Go example","walkthrough":"Wrapping preserves ErrMissing for errors.Is while adding the project operation for a human. The program prints once at the boundary. Replacing %w with %v would keep the message but lose this cause chain."},{"body":"Expose stable error categories only when they are part of the package contract. Implementation details can become accidental API commitments when wrapped. Panic is appropriate for violated programmer assumptions in some APIs, not an ordinary missing record or malformed request.","title":"Tradeoffs and the simpler alternative"},{"body":"Use errors.Is for stable sentinel categories and errors.As for documented structured error types. Messages can add operation context for a human but should not become machine parsing protocols. Wrap with %w only when exposing the cause is part of the API contract. Otherwise map to an application category and retain safe diagnostic context. A database missing-row error should not automatically become a permanent public dependency on the database driver.","code":"switch {\ncase errors.Is(err, ErrMissing):\n    // Map the documented absence contract at the transport boundary.\ncase errors.Is(err, context.DeadlineExceeded):\n    // Distinguish timeout from invalid input; retry only if safe.\ncase err != nil:\n    // Report a safe diagnostic once, with an operation identifier.\n}","language":"go","title":"Classify without parsing message text","walkthrough":"This is a focused layout or boundary fragment, not a second standalone program. Read it together with the complete worked example above."},{"body":"The layer knowing an operation is idempotent may choose a bounded retry; a low-level helper should not retry every failure blindly. A transport maps validation and authorization errors to appropriate responses without leaking SQL or credentials. Log once where the error is finally handled, while intermediate layers return useful context. An error can accompany useful partial output, so inspect the API contract before discarding data or returning early.","title":"Choose the layer that can recover"},{"body":"Assert errors.Is or errors.As for categories that callers are allowed to depend on, and check state was not partially committed after failure. Test a wrapped cancellation and a typed-nil implementation. Avoid comparing whole human messages unless their exact text is a deliberate contract. Panic and recover are not a substitute for expected validation errors. Do not recover a panic and silently return success; recover only at a defined boundary with a clear failed-operation result.","title":"Test cancellation and the public error promise"},{"body":"Expose stable error categories only when they are part of the package contract. Implementation details can become accidental API commitments when wrapped. Panic is appropriate for violated programmer assumptions in some APIs, not an ordinary missing record or malformed request.","title":"Practical limits and cautions"}],"takeaway":"Adds context while preserving a cause for errors.Is. Expose stable error categories only when they are part of the package contract. Implementation details can become accidental API commitments when wrapped. Panic is appropriate for violated programmer assumptions in some APIs, not an ordinary missing record or malformed request.","title":"Errors: preserve cause and choose one reporting boundary","unitID":"clean-code","wrongAnswers":["Logging at every layer improves signal automatically","Formatting with %v preserves the error chain"]},{"conceptTag":"clean.ownership","designGuide":{"cautions":["Deep structures need more than a shallow copy","Copies should be measured on hot paths"],"cost":"Low to medium","family":"Clean Go","flow":["Caller supplies mutable bytes","Constructor copies retained state","Accessor returns a separate copy"],"ratings":[],"strengths":["An object retains caller-owned mutable input","Unexpected aliasing causes hard-to-find changes"]},"hint":"The constructor copies input and Bytes copies output, so neither caller mutation changes the retained message.","id":"clean.ownership","introduction":"Make it clear whether a caller lends, shares or transfers a buffer. A slice is a view of a backing array, so assignment does not copy its elements. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Copies cost memory and time, so measure large buffers before copying everywhere.","objective":"Make it clear whether a caller lends, shares or transfers a buffer.","question":"Which statement best describes Ownership: copy mutable data deliberately?","references":["https://pkg.go.dev/bytes#Clone","https://go.dev/blog/slices-intro","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Defines who may retain and mutate shared data","reviewPrompt":"Ownership boundary","sections":[{"body":"A slice is a view of a backing array, so assignment does not copy its elements. An API that retains caller-owned bytes must define whether later mutation is allowed. Copying at an ownership boundary can be more valuable than making every method look immutable.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n)\n\ntype Message struct{ body []byte }\n\nfunc NewMessage(input []byte) Message { return Message{body: bytes.Clone(input)} }\nfunc (m Message) Bytes() []byte       { return bytes.Clone(m.body) }\n\nfunc main() {\n\tinput := []byte(\"go\")\n\tm := NewMessage(input)\n\tinput[0] = 'n'\n\toutput := m.Bytes()\n\toutput[0] = 'x'\n\tfmt.Println(string(m.Bytes()))\n}\n\n// Output:\n// go\n","language":"go","title":"A complete Go example","walkthrough":"The constructor copies input and Bytes copies output, so neither caller mutation changes the retained message. This makes the ownership contract concrete. It does not make arbitrary maps, nested pointers or concurrent methods safe automatically."},{"body":"Copies cost memory and time, so measure large buffers before copying everywhere. A documented transfer or read-only borrowing contract may be preferable in a hot path. Mutexes protect shared access only when every relevant access follows the same lock discipline.","title":"Tradeoffs and the simpler alternative"},{"body":"Returning a slice copies its descriptor, not its backing array. A caller can mutate shared elements even when append later allocates new storage. State whether the result is borrowed, immutable by convention or owned by the caller. Clone at the boundary when independent mutation is expected. A shallow clone of a slice of pointers still shares pointed-to values, so deep-copy behavior must match the actual domain structure.","title":"Describe ownership in the API contract"},{"body":"Either one goroutine owns the state and receives commands, a lock protects every relevant access, or callers receive isolated immutable snapshots. Mixing these models without a clear rule leaves races. A mutex guarding a map does not protect a slice stored in it after the method returns that slice. Return a snapshot under the lock, or keep later access inside the owner boundary. Test the aliasing case as well as running the race detector.","title":"Choose one concurrency model for mutable state"},{"body":"The code that successfully acquires a resource should define who closes it. Defer cleanup immediately after acquisition unless a documented ownership transfer occurs. A producer closes the channel it owns; arbitrary receivers should not close it to signal cancellation. Pass context for cancellation rather than sharing a mutable stop boolean. For a library API, document whether Close waits for goroutines and whether concurrent calls are supported.","title":"Make cleanup ownership visible"},{"body":"Copies cost memory and time, so measure large buffers before copying everywhere. A documented transfer or read-only borrowing contract may be preferable in a hot path. Mutexes protect shared access only when every relevant access follows the same lock discipline.","title":"Practical limits and cautions"},{"body":"The constructor copies input and Bytes copies output, so neither caller mutation changes the retained message. This makes the ownership contract concrete. It does not make arbitrary maps, nested pointers or concurrent methods safe automatically.","title":"How to read this example"}],"takeaway":"Defines who may retain and mutate shared data. Copies cost memory and time, so measure large buffers before copying everywhere. A documented transfer or read-only borrowing contract may be preferable in a hot path. Mutexes protect shared access only when every relevant access follows the same lock discipline.","title":"Ownership: copy mutable data deliberately","unitID":"clean-code","wrongAnswers":["Assigning a slice copies its backing array","A mutex fixes access that ignores the lock"]},{"conceptTag":"clean.configuration","designGuide":{"cautions":["Option interactions still need validation","Partial resource acquisition needs cleanup"],"cost":"Low","family":"Clean Go","flow":["Caller names configuration fields","Constructor validates combinations","Resources start only after validation"],"ratings":[],"strengths":["Invalid settings should fail at startup","An object needs stable invariants"]},"hint":"NewPool rejects zero workers and a queue smaller than the worker count. The successful caller receives a valid configuration. No goroutines are started in this example, which keeps validation separate from lifecycle and cleanup.","id":"clean.configuration","introduction":"Turn invalid setup into an explicit startup error. A constructor is a useful boundary for validating configuration that should remain true for an object’s lifetime. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use functional options only when they improve an evolving API.","objective":"Turn invalid setup into an explicit startup error.","question":"Which statement best describes Configuration: validate once at construction?","references":["https://go.dev/wiki/CodeReviewComments#useful-test-failures","https://pkg.go.dev/errors","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Rejects invalid combinations before acquiring resources","reviewPrompt":"Validated configuration","sections":[{"body":"A constructor is a useful boundary for validating configuration that should remain true for an object’s lifetime. Use a named config struct when options are already clear. Defaults should be deliberate, and a zero value should not silently disable a safety limit unless documented.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Config struct {\n\tWorkers    int\n\tQueueLimit int\n}\ntype Pool struct{ config Config }\n\nfunc NewPool(c Config) (*Pool, error) {\n\tif c.Workers <= 0 || c.QueueLimit < c.Workers {\n\t\treturn nil, errors.New(\"invalid pool limits\")\n\t}\n\treturn &Pool{config: c}, nil\n}\n\nfunc main() {\n\tp, err := NewPool(Config{Workers: 2, QueueLimit: 8})\n\tfmt.Println(p.config.Workers, err)\n\t_, err = NewPool(Config{Workers: 0})\n\tfmt.Println(err)\n}\n\n// Output:\n// 2 <nil>\n// invalid pool limits\n","language":"go","title":"A complete Go example","walkthrough":"NewPool rejects zero workers and a queue smaller than the worker count. The successful caller receives a valid configuration. No goroutines are started in this example, which keeps validation separate from lifecycle and cleanup."},{"body":"Use functional options only when they improve an evolving API. A constructor with many independent options can hide invalid combinations; validate the final configuration before opening files or starting goroutines, and clean up partial acquisition on later failure.","title":"Tradeoffs and the simpler alternative"},{"body":"Read environment variables and files at the executable boundary, parse durations and sizes into typed values, then validate required combinations before starting workers. Pass a completed configuration value to constructors. Re-reading environment variables deep in business logic makes tests and runtime behavior unpredictable. Apply defaults explicitly, and distinguish an omitted value from a meaningful zero. Do not log raw configuration if it contains secrets.","title":"Build a typed configuration at startup"},{"body":"Immutable configuration is simpler: restart a process to change it. If reload is required, parse and validate a whole new snapshot before atomically replacing the active one. Existing requests should see one consistent snapshot, not a mix of old and new fields. Some changes, such as a database destination, need resource lifecycle handling rather than swapping a string. Preserve the previous valid configuration when reload fails.","title":"Define which changes can happen at runtime"},{"body":"Cover an empty required address, malformed duration, negative retry count and a timeout smaller than a required operation budget. Verify secrets never appear in error text or diagnostic dumps. Constructors should fail with actionable context rather than leaving partially initialized workers alive. Functional options can help an API with many independent options, but they do not remove the need to validate incompatible choices after all options are applied.","title":"Test invalid combinations before deployment"},{"body":"Use functional options only when they improve an evolving API. A constructor with many independent options can hide invalid combinations; validate the final configuration before opening files or starting goroutines, and clean up partial acquisition on later failure.","title":"Practical limits and cautions"}],"takeaway":"Rejects invalid combinations before acquiring resources. Use functional options only when they improve an evolving API. A constructor with many independent options can hide invalid combinations; validate the final configuration before opening files or starting goroutines, and clean up partial acquisition on later failure.","title":"Configuration: validate once at construction","unitID":"clean-code","wrongAnswers":["More functional options always make an API clearer","Validation should wait until the first request"]},{"conceptTag":"clean.table-tests","designGuide":{"cautions":["Mocks can mirror implementation details","Fakes cannot prove a real database adapter works"],"cost":"Low","family":"Clean Go","flow":["Choose inputs that challenge the contract","Run the same observable operation","Compare values and error categories"],"ratings":[],"strengths":["Several boundary cases share the same behavior","Refactoring should preserve externally visible results"]},"hint":"The cases distinguish trimmed content from two forms of empty input and verify both the value and error presence. In a _test.go file, place the loop in TestNormalize and report the case with t.Errorf or t.Run rather than panic.","id":"clean.table-tests","introduction":"Test an observable contract with success and failure inputs. A table of cases makes differences explicit without copying the whole test body. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Add integration tests where real serialization, SQL or network contracts matter.","objective":"Test an observable contract with success and failure inputs.","question":"Which statement best describes Behavior tests: tables and boundary cases?","references":["https://go.dev/doc/tutorial/add-a-test","https://go.dev/doc/security/fuzz/","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Checks results and errors against a public contract","reviewPrompt":"Behavior-focused test","sections":[{"body":"A table of cases makes differences explicit without copying the whole test body. Include edge cases that can falsify the contract, not just another happy path. A fake should model behavior at a boundary rather than assert every internal call in a fixed order.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc Normalize(s string) (string, error) {\n\ts = strings.TrimSpace(s)\n\tif s == \"\" {\n\t\treturn \"\", errors.New(\"empty name\")\n\t}\n\treturn strings.ToLower(s), nil\n}\n\nfunc main() {\n\tcases := []struct {\n\t\tinput, want string\n\t\tfail        bool\n\t}{\n\t\t{\" Go \", \"go\", false}, {\"\", \"\", true}, {\"  \", \"\", true},\n\t}\n\tfor _, tc := range cases {\n\t\tgot, err := Normalize(tc.input)\n\t\tif got != tc.want || (err != nil) != tc.fail {\n\t\t\tpanic(\"contract failed\")\n\t\t}\n\t}\n\tfmt.Println(\"3 cases passed\")\n}\n\n// Output:\n// 3 cases passed\n","language":"go","title":"A complete Go example","walkthrough":"The cases distinguish trimmed content from two forms of empty input and verify both the value and error presence. In a _test.go file, place the loop in TestNormalize and report the case with t.Errorf or t.Run rather than panic."},{"body":"Add integration tests where real serialization, SQL or network contracts matter. Table shape alone does not make a test meaningful. Fuzz properties such as round-trip encoding or no panics when the input space is larger than the useful handpicked examples.","title":"Tradeoffs and the simpler alternative"},{"body":"For a transfer, cover success, insufficient balance, missing destination, cancellation and a durable-write failure. Include a boundary such as zero or maximum allowed amount. A table is an organization tool, not a reason to make unrelated assertions share a giant struct. Give each case a name describing the behavior, and compare the public result and durable effect rather than private helper calls.","title":"Derive cases from the behavior contract"},{"body":"A fake repository can verify application decisions, but it cannot prove a SQL transaction rolls back or an index enforces uniqueness. Keep a focused adapter contract test with the real database in a controlled environment. Avoid sleeping to guess when concurrent work finished; synchronize using channels or an observable completion boundary. Call t.Parallel only when the case owns isolated state and does not mutate shared environment or fixtures.","title":"Use real integration points where fakes cannot prove behavior"},{"body":"Inject time and randomness where the caller needs a predictable boundary, and wait for owned goroutines before a test returns. The race detector finds executions with conflicting accesses; one clean run does not prove every possible schedule safe. A benchmark needs representative input and allocation measurements, not an architecture score. Keep a failing regression for the user-visible defect while resisting tests that merely restate the implementation line by line.","title":"Treat nondeterminism as a design signal"},{"body":"Add integration tests where real serialization, SQL or network contracts matter. Table shape alone does not make a test meaningful. Fuzz properties such as round-trip encoding or no panics when the input space is larger than the useful handpicked examples.","title":"Practical limits and cautions"}],"takeaway":"Checks results and errors against a public contract. Add integration tests where real serialization, SQL or network contracts matter. Table shape alone does not make a test meaningful. Fuzz properties such as round-trip encoding or no panics when the input space is larger than the useful handpicked examples.","title":"Behavior tests: tables and boundary cases","unitID":"clean-code","wrongAnswers":["Must assert every private function call","Only happy paths belong in a table"]},{"conceptTag":"clean.refactoring","designGuide":{"cautions":["A weak test suite can preserve an unnoticed bug","Performance claims need representative measurements"],"cost":"Low to medium","family":"Clean Go","flow":["Capture existing boundary behavior","Extract one pure responsibility","Run focused tests before the next change"],"ratings":[],"strengths":["A feature is hard to test through I/O","A change can be divided into reviewable steps"]},"hint":"The boundary values 1000 and 1001 make the tariff transition visible.","id":"clean.refactoring","introduction":"Separate a behavior-preserving edit from a new requirement. A safe refactor starts with the behavior that must stay stable, then changes one structure at a time. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Run go test and go vet for correctness, race tests for exercised concurrency, and benchmarks for a suspected performance issue.","objective":"Separate a behavior-preserving edit from a new requirement.","question":"Which statement best describes Refactoring: make the safe change small?","references":["https://go.dev/doc/tutorial/add-a-test","https://go.dev/doc/articles/race_detector","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Changes structure while preserving an explicit contract","reviewPrompt":"Safe refactor","sections":[{"body":"A safe refactor starts with the behavior that must stay stable, then changes one structure at a time. Extract a pure decision from I/O so tests can describe it cheaply. Keep a correctness change or optimization in a separate step when possible, with a focused reason for each.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc ShippingCents(weight int) (int, error) {\n\tif weight <= 0 {\n\t\treturn 0, errors.New(\"positive weight required\")\n\t}\n\tif weight <= 1000 {\n\t\treturn 500, nil\n\t}\n\treturn 900, nil\n}\n\nfunc main() {\n\tfor _, weight := range []int{0, 1000, 1001} {\n\t\tcost, err := ShippingCents(weight)\n\t\tfmt.Println(weight, cost, err)\n\t}\n}\n\n// Output:\n// 0 0 positive weight required\n// 1000 500 <nil>\n// 1001 900 <nil>\n","language":"go","title":"A complete Go example","walkthrough":"The boundary values 1000 and 1001 make the tariff transition visible. Moving this decision out of a handler lets the same cases protect a later structural edit. The zero case verifies that invalid input is rejected before a quote is returned."},{"body":"Run go test and go vet for correctness, race tests for exercised concurrency, and benchmarks for a suspected performance issue. A shorter function is not automatically faster or clearer. Change a boundary only after its existing users and failure behavior are understood.","title":"Tradeoffs and the simpler alternative"},{"body":"First capture the public behavior around the seam you will move, including failure and partial-result semantics. Rename or extract one responsibility without changing the result, then make the new feature in a separate step. Moving code and redesigning all errors at once makes a regression difficult to locate. Keep commits small enough to explain what behavior should be identical and what deliberately changed.","title":"Separate a behavior change from a structural change"},{"body":"Place an adapter around the old implementation, move callers one at a time and compare results for safe read-only operations. For writes, choose one authoritative path; calling old and new payment implementations in parallel would duplicate effects. Keep backward-compatible data until rollback no longer depends on it. A clean package tree is not a rollback plan: durable schemas, queued events and public clients need their own compatibility strategy.","title":"Migrate a boundary in reversible stages"},{"body":"After callers use the new boundary, remove the old shared helper and inspect imports for hidden dependencies. Run focused unit and adapter tests and a small end-to-end path for the affected feature. Measure performance if the change introduces allocations, serialization or remote calls. Do not keep two permanent implementations just because both compile; unfinished migrations multiply maintenance cost and eventually let behavior diverge.","title":"Use deletion as the final proof of extraction"},{"body":"Run go test and go vet for correctness, race tests for exercised concurrency, and benchmarks for a suspected performance issue. A shorter function is not automatically faster or clearer. Change a boundary only after its existing users and failure behavior are understood.","title":"Practical limits and cautions"},{"body":"The boundary values 1000 and 1001 make the tariff transition visible. Moving this decision out of a handler lets the same cases protect a later structural edit. The zero case verifies that invalid input is rejected before a quote is returned.","title":"How to read this example"}],"takeaway":"Changes structure while preserving an explicit contract. Run go test and go vet for correctness, race tests for exercised concurrency, and benchmarks for a suspected performance issue. A shorter function is not automatically faster or clearer. Change a boundary only after its existing users and failure behavior are understood.","title":"Refactoring: make the safe change small","unitID":"clean-code","wrongAnswers":["May silently alter boundary behavior","Is proven correct by fewer lines alone"]},{"conceptTag":"clean.solid","designGuide":{"cautions":["Principles do not justify interfaces everywhere","Method sets cannot prove behavioral compatibility"],"cost":"Medium","family":"Clean Go","flow":["Consumer depends on a small contract","Wrapper preserves Read semantics","Concrete dependency is supplied explicitly"],"ratings":[],"strengths":["A design has multiple reasons to change","Substitutable implementations need shared semantics"]},"hint":"UpperReader decorates Read while preserving its byte count and error.","id":"clean.solid","introduction":"Translate responsibility, substitution and dependency inversion into Go contracts. Single responsibility concerns reasons to change. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Go has no class inheritance hierarchy to organize by default.","objective":"Translate responsibility, substitution and dependency inversion into Go contracts.","question":"Which statement best describes SOLID in Go: principles without class scaffolding?","references":["https://go.dev/wiki/CodeReviewComments#interfaces","https://pkg.go.dev/io#Reader","https://go.dev/wiki/CodeReviewComments"],"reviewAnswer":"Requires preserving behavior as well as method signatures","reviewPrompt":"Substitution in Go","sections":[{"body":"Single responsibility concerns reasons to change. Open/closed design isolates real variation. Substitution means preserving behavior promised to callers, not merely matching method signatures. Interface segregation and dependency inversion work well with small consumer-owned interfaces and explicit constructors.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\ntype UpperReader struct{ source io.Reader }\n\nfunc (r UpperReader) Read(p []byte) (int, error) {\n\tn, err := r.source.Read(p)\n\tfor i := 0; i < n; i++ {\n\t\tif p[i] >= 'a' && p[i] <= 'z' {\n\t\t\tp[i] -= 'a' - 'A'\n\t\t}\n\t}\n\treturn n, err\n}\n\nfunc main() {\n\tb, err := io.ReadAll(UpperReader{source: strings.NewReader(\"Go\")})\n\tfmt.Println(string(b), err)\n}\n\n// Output:\n// GO <nil>\n","language":"go","title":"A complete Go example","walkthrough":"UpperReader decorates Read while preserving its byte count and error. It changes ASCII letters only, which is an explicit scope rather than a Unicode claim. Consumers still use io.Reader, so the abstraction protects a behavior that actually varies."},{"body":"Go has no class inheritance hierarchy to organize by default. Favor composition and concrete values until substitution matters. A type can satisfy an interface and still violate its semantic contract, such as discarding partial reads; test those contracts rather than counting interfaces.","title":"Tradeoffs and the simpler alternative"},{"body":"Single responsibility asks which reason for change a package owns. Interface segregation favors small consumer contracts. Dependency inversion keeps business policy independent of transport and storage details. Open/closed can mean a function value or composed strategy rather than an inheritance hierarchy. Liskov substitution means an implementation preserves the promised behavior, not merely that its methods compile. These principles are review questions, not a requirement for five new abstraction layers.","title":"Translate principles into Go decisions"},{"body":"If a store promises that Get never mutates returned snapshots, an implementation returning an internal mutable slice violates the contract despite matching the interface. If one implementation ignores cancellation or changes missing-record semantics, callers cannot safely substitute it. Run the same contract suite against implementations. Use constructor validation to reject unsupported combinations rather than weakening the interface promise silently.","title":"Check substitution with behavioral examples"},{"body":"A small stable function is often better than a registry, factory and configurable strategy system for one use case. Introduce variation at a demonstrated seam, then keep dependencies explicit. A new requirement that changes a business rule is not automatically a failure of open/closed design. Evaluate how many files and contracts a realistic change touches, and whether the abstraction makes tests and ownership clearer. Prefer readable composition and concrete values over copying class-oriented ceremony.","title":"Balance extensibility against current complexity"},{"body":"Go has no class inheritance hierarchy to organize by default. Favor composition and concrete values until substitution matters. A type can satisfy an interface and still violate its semantic contract, such as discarding partial reads; test those contracts rather than counting interfaces.","title":"Practical limits and cautions"},{"body":"UpperReader decorates Read while preserving its byte count and error. It changes ASCII letters only, which is an explicit scope rather than a Unicode claim. Consumers still use io.Reader, so the abstraction protects a behavior that actually varies.","title":"How to read this example"}],"takeaway":"Requires preserving behavior as well as method signatures. Go has no class inheritance hierarchy to organize by default. Favor composition and concrete values until substitution matters. A type can satisfy an interface and still violate its semantic contract, such as discarding partial reads; test those contracts rather than counting interfaces.","title":"SOLID in Go: principles without class scaffolding","unitID":"clean-code","wrongAnswers":["Interface satisfaction proves all semantic behavior","SOLID requires inheritance trees in Go"]},{"conceptTag":"patterns.factory-method","designGuide":{"cautions":["Constructor injection may be simpler","Creation must define errors and cleanup ownership"],"cost":"Low to medium","family":"Creational pattern","flow":["Caller supplies a creation hook","Stable algorithm asks for a product","Algorithm uses the product contract"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["An algorithm should vary product creation","Tests need a predictable product implementation"]},"hint":"Report.Write owns the stable algorithm and calls the supplied creation hook.","id":"patterns.factory-method","introduction":"Vary product creation without duplicating the algorithm that uses it. The classic Factory Method lets an algorithm ask an overridable creation operation for a product. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use a plain constructor when the caller can create the dependency directly.","objective":"Vary product creation without duplicating the algorithm that uses it.","question":"Which statement best describes Factory Method: supply the creation step?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/io#Writer"],"reviewAnswer":"Varies creation through an algorithm’s supplied hook","reviewPrompt":"Factory Method in Go","sections":[{"body":"The classic Factory Method lets an algorithm ask an overridable creation operation for a product. Go usually replaces the inheritance hook with a function or small interface. Preserve that separation: a switch returning objects by name is a simple factory, not the full classic structure.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype Report struct{ NewWriter func() io.Writer }\n\nfunc (r Report) Write() io.Writer {\n\tw := r.NewWriter()\n\tfmt.Fprint(w, \"report\")\n\treturn w\n}\n\nfunc main() {\n\tr := Report{NewWriter: func() io.Writer { return &bytes.Buffer{} }}\n\tw := r.Write()\n\tfmt.Println(w.(*bytes.Buffer).String())\n}\n\n// Output:\n// report\n","language":"go","title":"A complete Go example","walkthrough":"Report.Write owns the stable algorithm and calls the supplied creation hook. main chooses a buffer product without rewriting the report logic. The type assertion is used only to inspect this known test product, not as the algorithm’s dependency."},{"body":"Use a plain constructor when the caller can create the dependency directly. Real writers can fail, so production report code should return write errors and define who closes the writer. A factory function should not hide expensive creation or ownership rules.","title":"Tradeoffs and the simpler alternative"},{"body":"Use a plain constructor when the caller can create the dependency directly. Real writers can fail, so production report code should return write errors and define who closes the writer. A factory function should not hide expensive creation or ownership rules.","title":"Practical limits and cautions"},{"body":"Report.Write owns the stable algorithm and calls the supplied creation hook. main chooses a buffer product without rewriting the report logic. The type assertion is used only to inspect this known test product, not as the algorithm’s dependency.","title":"How to read this example"}],"takeaway":"Varies creation through an algorithm’s supplied hook. Use a plain constructor when the caller can create the dependency directly. Real writers can fail, so production report code should return write errors and define who closes the writer. A factory function should not hide expensive creation or ownership rules.","title":"Factory Method: supply the creation step","unitID":"patterns-creational","wrongAnswers":["Requires subclassing a Go struct","Is any switch that returns a value"]},{"conceptTag":"patterns.abstract-factory","designGuide":{"cautions":["New product roles affect all factories","A configuration struct is often enough"],"cost":"Medium","family":"Creational pattern","flow":["Select a product family","Factory creates button and toggle","Client uses compatible products"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["Related product roles must vary together","Mixing integrations would be invalid"]},"hint":"Screen requests two distinct product roles from the same factory, keeping the family consistent.","id":"patterns.abstract-factory","introduction":"Create related products through one selected family. Abstract Factory selects a family of products that should work together. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values.","objective":"Create related products through one selected family.","question":"Which statement best describes Abstract Factory: compatible product families?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Creates compatible products from one selected family","reviewPrompt":"Abstract Factory","sections":[{"body":"Abstract Factory selects a family of products that should work together. A UI theme might create both buttons and toggles; a storage integration might create matching readers and writers. Returning one object with many options is configuration, not necessarily a product family.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Button struct{ theme string }\ntype Toggle struct{ theme string }\ntype Factory interface {\n\tButton() Button\n\tToggle() Toggle\n}\ntype Dark struct{}\n\nfunc (Dark) Button() Button   { return Button{theme: \"dark\"} }\nfunc (Dark) Toggle() Toggle   { return Toggle{theme: \"dark\"} }\nfunc Screen(f Factory) string { return f.Button().theme + \"/\" + f.Toggle().theme }\n\nfunc main() {\n\tfmt.Println(Screen(Dark{}))\n}\n\n// Output:\n// dark/dark\n","language":"go","title":"A complete Go example","walkthrough":"Screen requests two distinct product roles from the same factory, keeping the family consistent. Dark can be replaced with another factory implementing both methods. In a real package, keep constructors controlled if mixed families would violate invariants."},{"body":"This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values.","title":"Tradeoffs and the simpler alternative"},{"body":"Screen requests two distinct product roles from the same factory, keeping the family consistent. Dark can be replaced with another factory implementing both methods. In a real package, keep constructors controlled if mixed families would violate invariants.","title":"How to read this example"}],"takeaway":"Creates compatible products from one selected family. This helps when families vary together and incompatible combinations cause bugs. Adding a new product role changes every factory, so a config struct or a single constructor is often cheaper for a small stable set of values.","title":"Abstract Factory: compatible product families","unitID":"patterns-creational","wrongAnswers":["Constructs only one unrelated object","Makes adding a new product role free"]},{"conceptTag":"patterns.builder","designGuide":{"cautions":["A config literal may be easier to read","Reused builders can accidentally alias product data"],"cost":"Medium","family":"Creational pattern","flow":["Builder collects assembly steps","Build validates the combination","Product owns its retained values"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":2}],"strengths":["Assembly has repeated or ordered operations","A finished product must satisfy cross-field rules"]},"hint":"Build validates the path and copies tags into the finished Request. Adding another builder tag does not mutate the already built request. This is a staged mutable builder, not a promise of thread safety.","id":"patterns.builder","introduction":"Represent staged construction without making invalid results usable. Builder separates assembly steps from the finished value. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"A builder with one setter per field can obscure a clear struct literal. Use it for genuinely staged or repeated assembly and return validation errors. State whether a builder can be reused and whether products share backing storage.","objective":"Represent staged construction without making invalid results usable.","question":"Which statement best describes Builder: assemble then validate?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Validates assembled state before exposing the product","reviewPrompt":"Builder result","sections":[{"body":"Builder separates assembly steps from the finished value. In Go a named configuration struct is often sufficient; a builder becomes useful when assembly has repeated steps or derived data. Build should validate the final combination rather than assume every sequence was legal.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Request struct {\n\tPath string\n\tTags []string\n}\ntype Builder struct {\n\tpath string\n\ttags []string\n}\n\nfunc (b *Builder) Path(p string) { b.path = p }\nfunc (b *Builder) Tag(t string)  { b.tags = append(b.tags, t) }\nfunc (b Builder) Build() (Request, error) {\n\tif !strings.HasPrefix(b.path, \"/\") {\n\t\treturn Request{}, errors.New(\"absolute path required\")\n\t}\n\treturn Request{Path: b.path, Tags: append([]string(nil), b.tags...)}, nil\n}\n\nfunc main() {\n\tb := &Builder{}\n\tb.Path(\"/reports\")\n\tb.Tag(\"daily\")\n\tr, err := b.Build()\n\tb.Tag(\"later\")\n\tfmt.Println(r.Path, r.Tags, err)\n}\n\n// Output:\n// /reports [daily] <nil>\n","language":"go","title":"A complete Go example","walkthrough":"Build validates the path and copies tags into the finished Request. Adding another builder tag does not mutate the already built request. This is a staged mutable builder, not a promise of thread safety."},{"body":"A builder with one setter per field can obscure a clear struct literal. Use it for genuinely staged or repeated assembly and return validation errors. State whether a builder can be reused and whether products share backing storage.","title":"Tradeoffs and the simpler alternative"}],"takeaway":"Validates assembled state before exposing the product. A builder with one setter per field can obscure a clear struct literal. Use it for genuinely staged or repeated assembly and return validation errors. State whether a builder can be reused and whether products share backing storage.","title":"Builder: assemble then validate","unitID":"patterns-creational","wrongAnswers":["Every setter makes all later combinations valid","Must share mutable buffers with the builder"]},{"conceptTag":"patterns.prototype","designGuide":{"cautions":["Shallow copies can retain shared mutable elements","Resource handles should not be cloned"],"cost":"Low to medium","family":"Creational pattern","flow":["Select an existing configured value","Copy owned mutable collections","Customize an independent result"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":2}],"strengths":["Templates contain useful repeatable configuration","Callers need isolated editable drafts"]},"hint":"The clone owns a different slice backing array and a different map, so mutation does not change original. The elements here are immutable strings and integers; pointer or nested slice elements would require another deliberate copy decision.","id":"patterns.prototype","introduction":"Choose shallow or deep copying according to ownership. Prototype creates an object from an existing configured object. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method.","objective":"Choose shallow or deep copying according to ownership.","question":"Which statement best describes Prototype: copy a useful starting value?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/maps#Clone","https://pkg.go.dev/slices#Clone"],"reviewAnswer":"Copies the state needed for an independent starting value","reviewPrompt":"Prototype clone","sections":[{"body":"Prototype creates an object from an existing configured object. A Go struct assignment copies fields, but maps, slices and pointers may still refer to the original storage. Define what cloning promises before using a prototype as an independent editable draft.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"maps\"\n\t\"slices\"\n)\n\ntype Template struct {\n\tTags   []string\n\tLimits map[string]int\n}\n\nfunc (t Template) Clone() Template {\n\treturn Template{Tags: slices.Clone(t.Tags), Limits: maps.Clone(t.Limits)}\n}\n\nfunc main() {\n\toriginal := Template{Tags: []string{\"go\"}, Limits: map[string]int{\"cpu\": 2}}\n\tcopy := original.Clone()\n\tcopy.Tags[0] = \"rust\"\n\tcopy.Limits[\"cpu\"] = 4\n\tfmt.Println(original.Tags[0], original.Limits[\"cpu\"])\n}\n\n// Output:\n// go 2\n","language":"go","title":"A complete Go example","walkthrough":"The clone owns a different slice backing array and a different map, so mutation does not change original. The elements here are immutable strings and integers; pointer or nested slice elements would require another deliberate copy decision."},{"body":"Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method.","title":"Tradeoffs and the simpler alternative"}],"takeaway":"Copies the state needed for an independent starting value. Copying a network connection or mutex is not a valid general cloning strategy. Keep resource handles out of reusable prototypes. If a value is already small and immutable, an ordinary assignment is simpler than a named Clone method.","title":"Prototype: copy a useful starting value","unitID":"patterns-creational","wrongAnswers":["A struct assignment deeply clones every map","Cloning a live mutex is generally safe"]},{"conceptTag":"patterns.singleton","designGuide":{"cautions":["Global mutation hides coupling between tests","Once is not a transient-error retry policy"],"cost":"Medium","family":"Creational pattern","flow":["Owner creates a once function","First call constructs the value","Later calls receive that same value"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":2},{"scenario":"Independent distributed services","score":2}],"strengths":["One owner needs lazy immutable initialization","Creation should happen at most once"]},"hint":"The closure creates one Config for its owner and returns the same pointer twice.","id":"patterns.singleton","introduction":"Understand one-instance intent and choose an explicit lifetime. Singleton controls access to one instance. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"OnceValue caches a panic as well as a result; it is not a retry mechanism for transient startup failures.","objective":"Understand one-instance intent and choose an explicit lifetime.","question":"Which statement best describes Singleton: once does not mean global mutable state?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/sync#OnceValue"],"reviewAnswer":"Synchronizes creation but not later object mutation","reviewPrompt":"Once initialization","sections":[{"body":"Singleton controls access to one instance. Go can initialize once with sync.OnceValue, but a package-global mutable object hides dependencies and shares state across tests. Prefer one explicitly constructed application dependency unless unique identity is a genuine requirement.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Config struct{ Region string }\n\nfunc main() {\n\tcalls := 0\n\tload := sync.OnceValue(func() *Config { calls++; return &Config{Region: \"local\"} })\n\ta, b := load(), load()\n\tfmt.Println(a == b, calls)\n}\n\n// Output:\n// true 1\n","language":"go","title":"A complete Go example","walkthrough":"The closure creates one Config for its owner and returns the same pointer twice. OnceValue synchronizes initialization, not future mutation of Region. Keeping the owner local makes the lifetime visible and avoids a hidden process-wide dependency."},{"body":"OnceValue caches a panic as well as a result; it is not a retry mechanism for transient startup failures. Separate immutable configuration from mutable clients, and inject the latter. Shared uniqueness can complicate parallel tests, shutdown and replacement.","title":"Tradeoffs and the simpler alternative"},{"body":"OnceValue caches a panic as well as a result; it is not a retry mechanism for transient startup failures. Separate immutable configuration from mutable clients, and inject the latter. Shared uniqueness can complicate parallel tests, shutdown and replacement.","title":"Practical limits and cautions"},{"body":"The closure creates one Config for its owner and returns the same pointer twice. OnceValue synchronizes initialization, not future mutation of Region. Keeping the owner local makes the lifetime visible and avoids a hidden process-wide dependency.","title":"How to read this example"}],"takeaway":"Synchronizes creation but not later object mutation. OnceValue caches a panic as well as a result; it is not a retry mechanism for transient startup failures. Separate immutable configuration from mutable clients, and inject the latter. Shared uniqueness can complicate parallel tests, shutdown and replacement.","title":"Singleton: once does not mean global mutable state","unitID":"patterns-creational","wrongAnswers":["Makes every field access concurrency-safe","Automatically retries a failed initialization"]},{"conceptTag":"patterns.adapter","designGuide":{"cautions":["Error translation must preserve meaning","An unnecessary wrapper increases indirection"],"cost":"Low","family":"Structural pattern","flow":["Consumer expects Fahrenheit","Adapter converts units and method shape","Existing sensor supplies Celsius"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["An external API does not match the consumer","Conversions should stay out of domain policy"]},"hint":"SensorAdapter translates Celsius into Fahrenheit and satisfies the consumer’s method implicitly.","id":"patterns.adapter","introduction":"Keep conversion details at the boundary that needs them. An adapter lets an existing implementation satisfy a different caller contract. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use an adapter for an actual mismatch. If you own both sides and can make their contracts agree directly, another wrapper may add no value. Adapter changes the interface; Decorator usually preserves it while adding behavior.","objective":"Keep conversion details at the boundary that needs them.","question":"Which statement best describes Adapter: translate one contract into another?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Translates an existing interface for a different caller","reviewPrompt":"Adapter","sections":[{"body":"An adapter lets an existing implementation satisfy a different caller contract. It translates data or method shape while preserving meaningful errors. Keep units explicit: an adapter is a useful place to prevent two compatible-looking numbers from meaning different things.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype CelsiusSensor struct{}\n\nfunc (CelsiusSensor) Celsius() float64 { return 20 }\n\ntype Fahrenheit interface{ Fahrenheit() float64 }\ntype SensorAdapter struct{ source CelsiusSensor }\n\nfunc (a SensorAdapter) Fahrenheit() float64 { return a.source.Celsius()*9/5 + 32 }\nfunc Display(s Fahrenheit)                  { fmt.Println(s.Fahrenheit()) }\n\nfunc main() {\n\tDisplay(SensorAdapter{source: CelsiusSensor{}})\n}\n\n// Output:\n// 68\n","language":"go","title":"A complete Go example","walkthrough":"SensorAdapter translates Celsius into Fahrenheit and satisfies the consumer’s method implicitly. Display does not know the source API. In a real sensor adapter, also translate unavailable readings and calibration failures without inventing a valid zero temperature."},{"body":"Use an adapter for an actual mismatch. If you own both sides and can make their contracts agree directly, another wrapper may add no value. Adapter changes the interface; Decorator usually preserves it while adding behavior.","title":"Tradeoffs and the simpler alternative"},{"body":"SensorAdapter translates Celsius into Fahrenheit and satisfies the consumer’s method implicitly. Display does not know the source API. In a real sensor adapter, also translate unavailable readings and calibration failures without inventing a valid zero temperature.","title":"How to read this example"}],"takeaway":"Translates an existing interface for a different caller. Use an adapter for an actual mismatch. If you own both sides and can make their contracts agree directly, another wrapper may add no value. Adapter changes the interface; Decorator usually preserves it while adding behavior.","title":"Adapter: translate one contract into another","unitID":"patterns-structural","wrongAnswers":["Must preserve the original method shape","Is identical to a wrapper that only adds logging"]},{"conceptTag":"patterns.bridge","designGuide":{"cautions":["One variation axis may need only a function","More contracts increase navigation cost"],"cost":"Medium","family":"Structural pattern","flow":["Abstraction chooses content","Bridge delegates rendering","Implementation chooses output form"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["Two variation axes would multiply concrete types","Implementations should be reused by several abstractions"]},"hint":"Report data and rendering policy vary separately through composition. A different report abstraction can reuse the same renderer. The function contract stays small because only one operation varies in this example.","id":"patterns.bridge","introduction":"Compose an abstraction with a separately variable implementation. Bridge separates an abstraction from its implementation so each can vary independently. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"If only one dimension varies, Strategy or a direct function argument may describe the design more clearly.","objective":"Compose an abstraction with a separately variable implementation.","question":"Which statement best describes Bridge: two independent dimensions of variation?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Separates two independently varying design dimensions","reviewPrompt":"Bridge","sections":[{"body":"Bridge separates an abstraction from its implementation so each can vary independently. A report can choose its content shape while a renderer chooses output format. This is useful when otherwise every shape-format combination would become a distinct type.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Renderer func(string) string\ntype Report struct {\n\tTitle  string\n\tRender Renderer\n}\n\nfunc (r Report) Output() string { return r.Render(r.Title) }\nfunc Plain(s string) string     { return s }\nfunc Loud(s string) string      { return strings.ToUpper(s) }\n\nfunc main() {\n\tfmt.Println(Report{Title: \"daily\", Render: Plain}.Output())\n\tfmt.Println(Report{Title: \"weekly\", Render: Loud}.Output())\n}\n\n// Output:\n// daily\n// WEEKLY\n","language":"go","title":"A complete Go example","walkthrough":"Report data and rendering policy vary separately through composition. A different report abstraction can reuse the same renderer. The function contract stays small because only one operation varies in this example."},{"body":"If only one dimension varies, Strategy or a direct function argument may describe the design more clearly. Bridge is planned separation; Adapter often retrofits existing incompatible APIs. Do not add both layers when there is no second independent variation.","title":"Tradeoffs and the simpler alternative"},{"body":"If only one dimension varies, Strategy or a direct function argument may describe the design more clearly. Bridge is planned separation; Adapter often retrofits existing incompatible APIs. Do not add both layers when there is no second independent variation.","title":"Practical limits and cautions"}],"takeaway":"Separates two independently varying design dimensions. If only one dimension varies, Strategy or a direct function argument may describe the design more clearly. Bridge is planned separation; Adapter often retrofits existing incompatible APIs. Do not add both layers when there is no second independent variation.","title":"Bridge: two independent dimensions of variation","unitID":"patterns-structural","wrongAnswers":["Always repairs an incompatible legacy API","Requires one concrete type per combination"]},{"conceptTag":"patterns.composite","designGuide":{"cautions":["Cycles and depth need a policy","Uniform interfaces can expose meaningless leaf operations"],"cost":"Medium","family":"Structural pattern","flow":["Client calls one operation","Group delegates to children","Leaves compute the base result"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["A tree has meaningful uniform operations","Clients should not branch on leaf versus group"]},"hint":"File and Folder satisfy the same Size operation, so the root recursively sums to nine. The interface hides whether a child is a leaf or group. This example assumes an acyclic owned tree and small nonnegative sizes.","id":"patterns.composite","introduction":"Define recursive behavior while guarding the shape of the structure. Composite exposes one operation on both individual values and groups. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Uniform operations can be elegant, but a group-only mutation API need not be forced onto leaves.","objective":"Define recursive behavior while guarding the shape of the structure.","question":"Which statement best describes Composite: treat leaves and groups uniformly?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Gives leaves and groups a common recursive operation","reviewPrompt":"Composite","sections":[{"body":"Composite exposes one operation on both individual values and groups. A file tree can compute size by summing children, while a leaf reports its own size. Decide whether the structure is a true tree; cycles require detection or a different traversal contract.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Sized interface{ Size() int }\ntype File int\n\nfunc (f File) Size() int { return int(f) }\n\ntype Folder []Sized\n\nfunc (f Folder) Size() int {\n\tn := 0\n\tfor _, child := range f {\n\t\tn += child.Size()\n\t}\n\treturn n\n}\n\nfunc main() {\n\troot := Folder{File(4), Folder{File(2), File(3)}}\n\tfmt.Println(root.Size())\n}\n\n// Output:\n// 9\n","language":"go","title":"A complete Go example","walkthrough":"File and Folder satisfy the same Size operation, so the root recursively sums to nine. The interface hides whether a child is a leaf or group. This example assumes an acyclic owned tree and small nonnegative sizes."},{"body":"Uniform operations can be elegant, but a group-only mutation API need not be forced onto leaves. Define depth limits or iterative traversal for untrusted trees. Shared nodes and cycles change ownership and may cause duplicate counting or infinite recursion.","title":"Tradeoffs and the simpler alternative"},{"body":"Uniform operations can be elegant, but a group-only mutation API need not be forced onto leaves. Define depth limits or iterative traversal for untrusted trees. Shared nodes and cycles change ownership and may cause duplicate counting or infinite recursion.","title":"Practical limits and cautions"}],"takeaway":"Gives leaves and groups a common recursive operation. Uniform operations can be elegant, but a group-only mutation API need not be forced onto leaves. Define depth limits or iterative traversal for untrusted trees. Shared nodes and cycles change ownership and may cause duplicate counting or infinite recursion.","title":"Composite: treat leaves and groups uniformly","unitID":"patterns-structural","wrongAnswers":["Makes cycles impossible automatically","Requires every leaf to support child mutation"]},{"conceptTag":"patterns.decorator","designGuide":{"cautions":["Order can change results and visibility","Wrappers can hide optional capabilities"],"cost":"Low to medium","family":"Structural pattern","flow":["Caller sees the same operation","Wrapper adds a concern","Wrapped implementation performs the work"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":5}],"strengths":["Cross-cutting behavior should compose","A small interface makes wrapping clear"]},"hint":"Both wrappers retain Operation and delegate exactly once.","id":"patterns.decorator","introduction":"Wrap a small operation instead of constructing a type hierarchy. Decorator adds behavior around an object while retaining the interface clients already use. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Preserve cancellation, errors and optional interfaces that callers actually depend on.","objective":"Wrap a small operation instead of constructing a type hierarchy.","question":"Which statement best describes Decorator: add behavior while preserving the contract?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/net/http#ResponseController"],"reviewAnswer":"Adds behavior while retaining the consumer contract","reviewPrompt":"Decorator","sections":[{"body":"Decorator adds behavior around an object while retaining the interface clients already use. Go often expresses decoration with a function returning a function. Logging, metrics and authorization can use this shape, but wrapper order changes observable behavior.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Operation func(string) string\n\nfunc Trim(next Operation) Operation {\n\treturn func(s string) string { return next(strings.TrimSpace(s)) }\n}\nfunc Bracket(next Operation) Operation { return func(s string) string { return \"[\" + next(s) + \"]\" } }\n\nfunc main() {\n\tidentity := func(s string) string { return s }\n\tfmt.Println(Trim(Bracket(identity))(\" go \"))\n\tfmt.Println(Bracket(Trim(identity))(\" go \"))\n}\n\n// Output:\n// [go]\n// [go]\n","language":"go","title":"A complete Go example","walkthrough":"Both wrappers retain Operation and delegate exactly once. The shown input produces the same result for these two wrappers, but that does not prove commutativity: metrics around authorization may count rejected calls while metrics inside it may not."},{"body":"Preserve cancellation, errors and optional interfaces that callers actually depend on. A wrapper around http.ResponseWriter can accidentally hide streaming capabilities. Use a direct call when one fixed concern does not need composable wrapping.","title":"Tradeoffs and the simpler alternative"},{"body":"Preserve cancellation, errors and optional interfaces that callers actually depend on. A wrapper around http.ResponseWriter can accidentally hide streaming capabilities. Use a direct call when one fixed concern does not need composable wrapping.","title":"Practical limits and cautions"},{"body":"Both wrappers retain Operation and delegate exactly once. The shown input produces the same result for these two wrappers, but that does not prove commutativity: metrics around authorization may count rejected calls while metrics inside it may not.","title":"How to read this example"}],"takeaway":"Adds behavior while retaining the consumer contract. Preserve cancellation, errors and optional interfaces that callers actually depend on. A wrapper around http.ResponseWriter can accidentally hide streaming capabilities. Use a direct call when one fixed concern does not need composable wrapping.","title":"Decorator: add behavior while preserving the contract","unitID":"patterns-structural","wrongAnswers":["Always changes to a different interface","Wrapper order can never affect behavior"]},{"conceptTag":"patterns.facade","designGuide":{"cautions":["One convenience method is not a transaction","Broad facades can become god objects"],"cost":"Low to medium","family":"Structural pattern","flow":["Client requests one workflow","Facade coordinates subsystem steps","Subsystems retain their own responsibilities"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":4}],"strengths":["Clients repeat the same orchestration","A subsystem API exposes too much detail"]},"hint":"Buy hides two local state changes behind one operation and validates before mutating.","id":"patterns.facade","introduction":"Simplify orchestration without pretending several effects are atomic. A facade offers a convenient operation over several lower-level components. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"A facade can become a god object if it owns every policy.","objective":"Simplify orchestration without pretending several effects are atomic.","question":"Which statement best describes Facade: one useful entry point over a subsystem?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Provides a focused entry point to a subsystem","reviewPrompt":"Facade","sections":[{"body":"A facade offers a convenient operation over several lower-level components. It can coordinate validation, inventory and notification, but convenience does not provide a transaction. The facade should report which promises it can actually make if a later step fails.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Checkout struct {\n\tStock int\n\tSent  int\n}\n\nfunc (c *Checkout) Buy(n int) error {\n\tif n <= 0 || n > c.Stock {\n\t\treturn errors.New(\"invalid quantity\")\n\t}\n\tc.Stock -= n\n\tc.Sent++\n\treturn nil\n}\n\nfunc main() {\n\tc := &Checkout{Stock: 4}\n\tfmt.Println(c.Buy(2))\n\tfmt.Println(c.Stock, c.Sent)\n}\n\n// Output:\n// <nil>\n// 2 1\n","language":"go","title":"A complete Go example","walkthrough":"Buy hides two local state changes behind one operation and validates before mutating. This single-owner in-memory example cannot fail after validation. Replacing Sent with an email or payment call introduces a new failure boundary that must be designed explicitly."},{"body":"A facade can become a god object if it owns every policy. Keep it focused on one client workflow, delegate domain rules, and use transactions or durable workflows where partial effects matter. A simple helper function can be the whole facade in Go.","title":"Tradeoffs and the simpler alternative"},{"body":"A facade can become a god object if it owns every policy. Keep it focused on one client workflow, delegate domain rules, and use transactions or durable workflows where partial effects matter. A simple helper function can be the whole facade in Go.","title":"Practical limits and cautions"},{"body":"Buy hides two local state changes behind one operation and validates before mutating. This single-owner in-memory example cannot fail after validation. Replacing Sent with an email or payment call introduces a new failure boundary that must be designed explicitly.","title":"How to read this example"}],"takeaway":"Provides a focused entry point to a subsystem. A facade can become a god object if it owns every policy. Keep it focused on one client workflow, delegate domain rules, and use transactions or durable workflows where partial effects matter. A simple helper function can be the whole facade in Go.","title":"Facade: one useful entry point over a subsystem","unitID":"patterns-structural","wrongAnswers":["Makes independent remote effects atomic","Must own all domain rules"]},{"conceptTag":"patterns.flyweight","designGuide":{"cautions":["Intern tables can retain unused data","Mutable shared state breaks independence"],"cost":"Medium","family":"Structural pattern","flow":["Catalog reuses one intrinsic glyph","Placement supplies external position","Many logical uses share immutable data"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["Many objects repeat sizable immutable data","Extrinsic state can stay at each call site"]},"hint":"Two placements share the same Glyph pointer but retain different positions.","id":"patterns.flyweight","introduction":"Separate reusable data from per-use context before optimizing memory. Flyweight shares intrinsic state across many logical objects while callers supply extrinsic context. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"An unbounded intern table can retain data forever and consume more memory than it saves.","objective":"Separate reusable data from per-use context before optimizing memory.","question":"Which statement best describes Flyweight: share immutable intrinsic state?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://go.dev/doc/gc-guide"],"reviewAnswer":"Shares immutable intrinsic state across many uses","reviewPrompt":"Flyweight","sections":[{"body":"Flyweight shares intrinsic state across many logical objects while callers supply extrinsic context. A glyph shape can be shared while its position belongs to each placement. The optimization is useful only when repeated retained data is large enough to matter.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Glyph struct{ shape string }\ntype Catalog struct{ glyphs map[string]*Glyph }\n\nfunc (c *Catalog) Get(shape string) *Glyph {\n\tif g := c.glyphs[shape]; g != nil {\n\t\treturn g\n\t}\n\tg := &Glyph{shape: shape}\n\tc.glyphs[shape] = g\n\treturn g\n}\n\ntype Placement struct {\n\tGlyph *Glyph\n\tX     int\n}\n\nfunc main() {\n\tc := Catalog{glyphs: make(map[string]*Glyph)}\n\ta := Placement{Glyph: c.Get(\"G\"), X: 1}\n\tb := Placement{Glyph: c.Get(\"G\"), X: 8}\n\tfmt.Println(a.Glyph == b.Glyph, a.X, b.X)\n}\n\n// Output:\n// true 1 8\n","language":"go","title":"A complete Go example","walkthrough":"Two placements share the same Glyph pointer but retain different positions. Treat shape as immutable after registration. The map is owned by one goroutine here; sharing Catalog concurrently would require synchronization or immutable publication."},{"body":"An unbounded intern table can retain data forever and consume more memory than it saves. Measure object counts and retained size, bound the cache where necessary, and do not share mutable per-use fields such as selection or position inside the flyweight.","title":"Tradeoffs and the simpler alternative"},{"body":"An unbounded intern table can retain data forever and consume more memory than it saves. Measure object counts and retained size, bound the cache where necessary, and do not share mutable per-use fields such as selection or position inside the flyweight.","title":"Practical limits and cautions"},{"body":"Two placements share the same Glyph pointer but retain different positions. Treat shape as immutable after registration. The map is owned by one goroutine here; sharing Catalog concurrently would require synchronization or immutable publication.","title":"How to read this example"}],"takeaway":"Shares immutable intrinsic state across many uses. An unbounded intern table can retain data forever and consume more memory than it saves. Measure object counts and retained size, bound the cache where necessary, and do not share mutable per-use fields such as selection or position inside the flyweight.","title":"Flyweight: share immutable intrinsic state","unitID":"patterns-structural","wrongAnswers":["Shares each object’s mutable position","Guarantees an unbounded cache saves memory"]},{"conceptTag":"patterns.proxy","designGuide":{"cautions":["Freshness and invalidation are correctness rules","Caches need concurrency and size policies"],"cost":"Medium","family":"Structural pattern","flow":["Caller invokes the subject contract","Proxy decides whether to delegate","Real subject supplies the value"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":4}],"strengths":["Access needs caching, authorization or laziness","The stand-in can preserve the contract"]},"hint":"The proxy invokes its subject once for the repeated key and returns the cached value on the second call. The closure is deliberately single-owner and unbounded for this tiny example; it is not a concurrent production cache.","id":"patterns.proxy","introduction":"Make caching or lazy access preserve the caller’s expectations. Proxy stands in for a real subject and controls access, for example with caching, authorization or lazy construction. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Choose a TTL or invalidation policy for changing data and include authorization scope in cache keys where needed.","objective":"Make caching or lazy access preserve the caller’s expectations.","question":"Which statement best describes Proxy: control access to an existing operation?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Controls access while preserving the subject interface","reviewPrompt":"Proxy","sections":[{"body":"Proxy stands in for a real subject and controls access, for example with caching, authorization or lazy construction. It retains the subject’s interface. A cache is correct only when its key, lifetime and invalidation rules match the semantics of the underlying operation.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Lookup func(string) string\n\nfunc Cached(next Lookup) Lookup {\n\tcache := make(map[string]string)\n\treturn func(key string) string {\n\t\tif value, ok := cache[key]; ok {\n\t\t\treturn value\n\t\t}\n\t\tvalue := next(key)\n\t\tcache[key] = value\n\t\treturn value\n\t}\n}\n\nfunc main() {\n\tcalls := 0\n\tlookup := Cached(func(key string) string { calls++; return \"value:\" + key })\n\tfmt.Println(lookup(\"go\"))\n\tfmt.Println(lookup(\"go\"))\n\tfmt.Println(calls)\n}\n\n// Output:\n// value:go\n// value:go\n// 1\n","language":"go","title":"A complete Go example","walkthrough":"The proxy invokes its subject once for the repeated key and returns the cached value on the second call. The closure is deliberately single-owner and unbounded for this tiny example; it is not a concurrent production cache."},{"body":"Choose a TTL or invalidation policy for changing data and include authorization scope in cache keys where needed. Distinguish a cached empty value from a cache miss. If callers need fresh state, a direct lookup may be the only correct behavior.","title":"Tradeoffs and the simpler alternative"},{"body":"Choose a TTL or invalidation policy for changing data and include authorization scope in cache keys where needed. Distinguish a cached empty value from a cache miss. If callers need fresh state, a direct lookup may be the only correct behavior.","title":"Practical limits and cautions"}],"takeaway":"Controls access while preserving the subject interface. Choose a TTL or invalidation policy for changing data and include authorization scope in cache keys where needed. Distinguish a cached empty value from a cache miss. If callers need fresh state, a direct lookup may be the only correct behavior.","title":"Proxy: control access to an existing operation","unitID":"patterns-structural","wrongAnswers":["Always changes the interface like an Adapter","A cache never changes freshness semantics"]},{"conceptTag":"patterns.strategy","designGuide":{"cautions":["Mutation and errors belong in the contract","A small fixed switch may be simpler"],"cost":"Low","family":"Behavioral pattern","flow":["Caller selects an algorithm","Context owns stable workflow","Strategy performs the varying step"],"ratings":[{"scenario":"Small tool or CLI","score":5},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["Algorithms vary independently of the workflow","Tests need deterministic alternative behavior"]},"hint":"Present controls copying and delegates ordering to the selected function.","id":"patterns.strategy","introduction":"Pass interchangeable behavior through a function or small interface. Strategy isolates an algorithm that changes independently of its caller. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently.","objective":"Pass interchangeable behavior through a function or small interface.","question":"Which statement best describes Strategy: choose an algorithm explicitly?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/sort"],"reviewAnswer":"Makes a varying algorithm an explicit dependency","reviewPrompt":"Strategy","sections":[{"body":"Strategy isolates an algorithm that changes independently of its caller. Go function values cover many one-method strategies without extra types. Select the strategy at the composition boundary and keep domain inputs clear instead of switching on a global mode in every call.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype Rank func([]int)\n\nfunc Present(values []int, rank Rank) []int {\n\tcopy := append([]int(nil), values...)\n\trank(copy)\n\treturn copy\n}\n\nfunc main() {\n\tvalues := []int{3, 1, 2}\n\tfmt.Println(Present(values, sort.Ints))\n\tfmt.Println(values)\n}\n\n// Output:\n// [1 2 3]\n// [3 1 2]\n","language":"go","title":"A complete Go example","walkthrough":"Present controls copying and delegates ordering to the selected function. The original slice remains unchanged, so strategy selection does not surprise its caller with mutation. A reverse ordering function could be supplied without editing Present."},{"body":"Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently.","title":"Tradeoffs and the simpler alternative"},{"body":"Present controls copying and delegates ordering to the selected function. The original slice remains unchanged, so strategy selection does not surprise its caller with mutation. A reverse ordering function could be supplied without editing Present.","title":"How to read this example"}],"takeaway":"Makes a varying algorithm an explicit dependency. Use direct branching for a small fixed choice that does not need independent extension. A strategy is not a justification for a new interface around every expression. Document whether it may mutate input, return errors or run concurrently.","title":"Strategy: choose an algorithm explicitly","unitID":"patterns-behavioral","wrongAnswers":["Requires an inheritance hierarchy","Should be selected through hidden global state"]},{"conceptTag":"patterns.command","designGuide":{"cautions":["Undo assumes a defined state history","Durable commands need explicit schemas"],"cost":"Medium","family":"Behavioral pattern","flow":["Create action with receiver and arguments","Execute through a command value","Restore prior state only where valid"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":4}],"strengths":["Actions need queuing, history or local undo","The invoker should not know receiver details"]},"hint":"Rename captures the receiver, requested name and old name. Do is guarded against repetition; Undo restores the prior value. This assumes no independent mutation between execution and undo and one owner of the receiver.","id":"patterns.command","introduction":"Make actions queueable or reversible without claiming every effect can be undone. Command packages an operation and its receiver into a value that can be executed later. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"For durable queues, serialize a command schema and validate it on receipt; a closure cannot survive process exit.","objective":"Make actions queueable or reversible without claiming every effect can be undone.","question":"Which statement best describes Command: represent an action as a value?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Captures an action and the data needed to execute it","reviewPrompt":"Command value","sections":[{"body":"Command packages an operation and its receiver into a value that can be executed later. It can support local undo when enough previous state is retained. Sending an email or charging a remote payment is not reversed by merely invoking a method named Undo.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Rename struct {\n\ttarget         *string\n\tnext, previous string\n\tdone           bool\n}\n\nfunc (c *Rename) Do() {\n\tif c.done {\n\t\treturn\n\t}\n\tc.previous = *c.target\n\t*c.target = c.next\n\tc.done = true\n}\nfunc (c *Rename) Undo() {\n\tif !c.done {\n\t\treturn\n\t}\n\t*c.target = c.previous\n\tc.done = false\n}\n\nfunc main() {\n\tname := \"draft\"\n\tc := &Rename{target: &name, next: \"report\"}\n\tc.Do()\n\tfmt.Println(name)\n\tc.Undo()\n\tfmt.Println(name)\n}\n\n// Output:\n// report\n// draft\n","language":"go","title":"A complete Go example","walkthrough":"Rename captures the receiver, requested name and old name. Do is guarded against repetition; Undo restores the prior value. This assumes no independent mutation between execution and undo and one owner of the receiver."},{"body":"For durable queues, serialize a command schema and validate it on receipt; a closure cannot survive process exit. Undo of external work often needs a compensating business action with its own possible failures. Use a direct function for one immediate action.","title":"Tradeoffs and the simpler alternative"},{"body":"For durable queues, serialize a command schema and validate it on receipt; a closure cannot survive process exit. Undo of external work often needs a compensating business action with its own possible failures. Use a direct function for one immediate action.","title":"Practical limits and cautions"}],"takeaway":"Captures an action and the data needed to execute it. For durable queues, serialize a command schema and validate it on receipt; a closure cannot survive process exit. Undo of external work often needs a compensating business action with its own possible failures. Use a direct function for one immediate action.","title":"Command: represent an action as a value","unitID":"patterns-behavioral","wrongAnswers":["Any external effect can be perfectly undone","A closure alone is a durable message format"]},{"conceptTag":"patterns.chain","designGuide":{"cautions":["Short-circuit order changes behavior","Silent swallowing makes failures hard to trace"],"cost":"Low to medium","family":"Behavioral pattern","flow":["First handler checks the request","Failure short-circuits the chain","Next handler receives accepted input"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":5}],"strengths":["Handlers can independently accept or reject","Middleware concerns should be composable"]},"hint":"Validate delegates in order and returns immediately on an error. The second check is never asked about an empty string after the first failure. An HTTP middleware chain can use a similar continuation shape with a next handler.","id":"patterns.chain","introduction":"Stop or delegate deliberately and make short-circuit order visible. A chain passes a request through handlers that can decide whether to continue. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Ordering is part of behavior: authentication should usually precede work that leaks private data.","objective":"Stop or delegate deliberately and make short-circuit order visible.","question":"Which statement best describes Chain of Responsibility: ordered handlers?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/net/http#Handler"],"reviewAnswer":"May handle, reject or delegate in a defined order","reviewPrompt":"Responsibility chain","sections":[{"body":"A chain passes a request through handlers that can decide whether to continue. Validation commonly stops at the first failure. Unlike an unconditional pipeline, a responsibility chain defines which handler accepts, rejects or delegates the request.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Check func(string) error\n\nfunc Validate(input string, checks ...Check) error {\n\tfor _, check := range checks {\n\t\tif err := check(input); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\nfunc NonEmpty(s string) error {\n\tif strings.TrimSpace(s) == \"\" {\n\t\treturn errors.New(\"empty\")\n\t}\n\treturn nil\n}\nfunc Short(s string) error {\n\tif len(s) > 5 {\n\t\treturn errors.New(\"too long\")\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tfmt.Println(Validate(\"\", NonEmpty, Short))\n\tfmt.Println(Validate(\"gopher\", NonEmpty, Short))\n}\n\n// Output:\n// empty\n// too long\n","language":"go","title":"A complete Go example","walkthrough":"Validate delegates in order and returns immediately on an error. The second check is never asked about an empty string after the first failure. An HTTP middleware chain can use a similar continuation shape with a next handler."},{"body":"Ordering is part of behavior: authentication should usually precede work that leaks private data. Keep chains observable and avoid handlers that silently swallow failures. If every step must always run, an explicit sequence or result-collecting validator may be clearer.","title":"Tradeoffs and the simpler alternative"},{"body":"Ordering is part of behavior: authentication should usually precede work that leaks private data. Keep chains observable and avoid handlers that silently swallow failures. If every step must always run, an explicit sequence or result-collecting validator may be clearer.","title":"Practical limits and cautions"}],"takeaway":"May handle, reject or delegate in a defined order. Ordering is part of behavior: authentication should usually precede work that leaks private data. Keep chains observable and avoid handlers that silently swallow failures. If every step must always run, an explicit sequence or result-collecting validator may be clearer.","title":"Chain of Responsibility: ordered handlers","unitID":"patterns-behavioral","wrongAnswers":["Always executes every later handler","Makes handler order irrelevant"]},{"conceptTag":"patterns.iterator","designGuide":{"cautions":["Errors and cleanup need explicit contracts","A slice range may already be sufficient"],"cost":"Low","family":"Behavioral pattern","flow":["Producer generates a value","Consumer receives it through yield","False return stops production"],"ratings":[{"scenario":"Small tool or CLI","score":5},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["Traversal should hide collection representation","Values can be produced lazily"]},"hint":"CountTo hides how values are generated and stops immediately after the caller breaks at two. iter.Seq is available from Go 1.23. The iterator uses no goroutine or channel because synchronous production is enough.","id":"patterns.iterator","introduction":"Use iter.Seq or a small Next API and honor early termination. Iterator gives callers sequential access without revealing collection internals. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"For fallible streams, define how errors are delivered, such as iter.Seq2[Value, error] or an Err method.","objective":"Use iter.Seq or a small Next API and honor early termination.","question":"Which statement best describes Iterator: yield values without exposing storage?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/iter"],"reviewAnswer":"Must stop producing when yield returns false","reviewPrompt":"Iterator yield","sections":[{"body":"Iterator gives callers sequential access without revealing collection internals. Modern Go supports range over iterator functions through iter.Seq. A producer must stop when yield returns false; continuing work after the caller breaks wastes resources and can violate the iterator contract.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"iter\"\n)\n\nfunc CountTo(n int) iter.Seq[int] {\n\treturn func(yield func(int) bool) {\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tif !yield(i) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tfor n := range CountTo(5) {\n\t\tfmt.Println(n)\n\t\tif n == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// Output:\n// 1\n// 2\n","language":"go","title":"A complete Go example","walkthrough":"CountTo hides how values are generated and stops immediately after the caller breaks at two. iter.Seq is available from Go 1.23. The iterator uses no goroutine or channel because synchronous production is enough."},{"body":"For fallible streams, define how errors are delivered, such as iter.Seq2[Value, error] or an Err method. Resource-owning iterators need cleanup on early termination. Ranging a slice is simpler when the caller already owns a small in-memory collection.","title":"Tradeoffs and the simpler alternative"},{"body":"For fallible streams, define how errors are delivered, such as iter.Seq2[Value, error] or an Err method. Resource-owning iterators need cleanup on early termination. Ranging a slice is simpler when the caller already owns a small in-memory collection.","title":"Practical limits and cautions"}],"takeaway":"Must stop producing when yield returns false. For fallible streams, define how errors are delivered, such as iter.Seq2[Value, error] or an Err method. Resource-owning iterators need cleanup on early termination. Ranging a slice is simpler when the caller already owns a small in-memory collection.","title":"Iterator: yield values without exposing storage","unitID":"patterns-behavioral","wrongAnswers":["Needs a goroutine for every sequence","May ignore early termination"]},{"conceptTag":"patterns.mediator","designGuide":{"cautions":["An oversized mediator becomes a god object","Two simple peers may not need coordination machinery"],"cost":"Medium","family":"Behavioral pattern","flow":["Participants expose focused operations","Mediator decides the interaction order","Participants stay independent of one another"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["Many peers otherwise reference one another","A workflow needs one place for coordination rules"]},"hint":"Submit owns the collaboration rule: notification only follows valid input. The two collaborators do not reference each other. This uses function dependencies because the roles are small and their lifetime is controlled by main.","id":"patterns.mediator","introduction":"Let participants communicate through a focused coordinator. Mediator moves interaction rules out of a set of objects that otherwise know one another directly. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"As participants grow, split mediators by use case instead of accumulating unrelated branches.","objective":"Let participants communicate through a focused coordinator.","question":"Which statement best describes Mediator: centralize collaboration deliberately?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Centralizes interaction rules among collaborators","reviewPrompt":"Mediator","sections":[{"body":"Mediator moves interaction rules out of a set of objects that otherwise know one another directly. A checkout coordinator can connect validation and notification without making each participant depend on every other. The mediator should represent a focused workflow rather than become the whole application.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Mediator struct {\n\tvalidate func(string) bool\n\tnotify   func(string)\n}\n\nfunc (m Mediator) Submit(name string) bool {\n\tif !m.validate(name) {\n\t\treturn false\n\t}\n\tm.notify(name)\n\treturn true\n}\n\nfunc main() {\n\tsent := \"\"\n\tm := Mediator{validate: func(s string) bool { return s != \"\" }, notify: func(s string) { sent = s }}\n\tfmt.Println(m.Submit(\"Ada\"), sent)\n\tfmt.Println(m.Submit(\"\"))\n}\n\n// Output:\n// true Ada\n// false\n","language":"go","title":"A complete Go example","walkthrough":"Submit owns the collaboration rule: notification only follows valid input. The two collaborators do not reference each other. This uses function dependencies because the roles are small and their lifetime is controlled by main."},{"body":"As participants grow, split mediators by use case instead of accumulating unrelated branches. A facade mainly simplifies client access; a mediator coordinates participant interaction. Direct calls are easier when only two simple components collaborate once.","title":"Tradeoffs and the simpler alternative"},{"body":"As participants grow, split mediators by use case instead of accumulating unrelated branches. A facade mainly simplifies client access; a mediator coordinates participant interaction. Direct calls are easier when only two simple components collaborate once.","title":"Practical limits and cautions"}],"takeaway":"Centralizes interaction rules among collaborators. As participants grow, split mediators by use case instead of accumulating unrelated branches. A facade mainly simplifies client access; a mediator coordinates participant interaction. Direct calls are easier when only two simple components collaborate once.","title":"Mediator: centralize collaboration deliberately","unitID":"patterns-behavioral","wrongAnswers":["Should absorb every unrelated workflow","Requires participants to know each other directly"]},{"conceptTag":"patterns.memento","designGuide":{"cautions":["History can retain substantial memory","Concurrent edits need a restore conflict policy"],"cost":"Medium","family":"Behavioral pattern","flow":["Originator creates an owned snapshot","Caretaker retains opaque history","Originator validates and restores"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":2}],"strengths":["Local undo needs previous object state","History should not depend on internal field details"]},"hint":"The snapshot copies lines on save and restore, preventing later edits from changing the saved history.","id":"patterns.memento","introduction":"Let the owner define what a valid snapshot contains. Memento stores state so its owner can restore a previous version without exposing editable internals to the caretaker. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Large histories need memory limits, deltas or durable versioning.","objective":"Let the owner define what a valid snapshot contains.","question":"Which statement best describes Memento: retain a restorable snapshot?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/slices#Clone"],"reviewAnswer":"Lets the owner restore previously captured state","reviewPrompt":"Memento snapshot","sections":[{"body":"Memento stores state so its owner can restore a previous version without exposing editable internals to the caretaker. In Go, use unexported snapshot fields and copy mutable collections. A history manager should not need to understand every invariant inside the edited object.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n)\n\ntype Snapshot struct{ lines []string }\ntype Document struct{ lines []string }\n\nfunc (d Document) Save() Snapshot      { return Snapshot{lines: slices.Clone(d.lines)} }\nfunc (d *Document) Restore(s Snapshot) { d.lines = slices.Clone(s.lines) }\n\nfunc main() {\n\td := Document{lines: []string{\"first\"}}\n\ts := d.Save()\n\td.lines[0] = \"changed\"\n\td.Restore(s)\n\tfmt.Println(d.lines[0])\n}\n\n// Output:\n// first\n","language":"go","title":"A complete Go example","walkthrough":"The snapshot copies lines on save and restore, preventing later edits from changing the saved history. The originator owns both operations. Across package boundaries the unexported fields keep the caretaker from modifying snapshot internals directly."},{"body":"Large histories need memory limits, deltas or durable versioning. Snapshots of external resources cannot rewind the outside world. For simple value types an ordinary copy may be sufficient; for concurrent editing a stale restore needs a conflict policy.","title":"Tradeoffs and the simpler alternative"},{"body":"Large histories need memory limits, deltas or durable versioning. Snapshots of external resources cannot rewind the outside world. For simple value types an ordinary copy may be sufficient; for concurrent editing a stale restore needs a conflict policy.","title":"Practical limits and cautions"},{"body":"The snapshot copies lines on save and restore, preventing later edits from changing the saved history. The originator owns both operations. Across package boundaries the unexported fields keep the caretaker from modifying snapshot internals directly.","title":"How to read this example"}],"takeaway":"Lets the owner restore previously captured state. Large histories need memory limits, deltas or durable versioning. Snapshots of external resources cannot rewind the outside world. For simple value types an ordinary copy may be sufficient; for concurrent editing a stale restore needs a conflict policy.","title":"Memento: retain a restorable snapshot","unitID":"patterns-behavioral","wrongAnswers":["Can rewind external effects automatically","Should expose all mutable internals to the caretaker"]},{"conceptTag":"patterns.observer","designGuide":{"cautions":["Slow callbacks can block the producer","Subscriptions can retain objects unexpectedly"],"cost":"Medium","family":"Behavioral pattern","flow":["Listener subscribes to a subject","Subject notifies registered listeners","Owner unsubscribes at end of lifetime"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":3}],"strengths":["Several local components react to changes","The subject should not know listener types"]},"hint":"The subscription returns its own cleanup operation. After stop, a later notification has no effect on total. The example assumes a single owner, no reentrant map mutation and listeners whose order does not matter.","id":"patterns.observer","introduction":"Keep notification lifetime and delivery semantics explicit. Observer lets interested listeners subscribe to changes without the subject knowing their concrete types. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Decide whether delivery is synchronous, ordered, droppable or buffered before introducing goroutines.","objective":"Keep notification lifetime and delivery semantics explicit.","question":"Which statement best describes Observer: subscribe, notify and unsubscribe?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Needs explicit delivery and unsubscribe semantics","reviewPrompt":"Observer subscription","sections":[{"body":"Observer lets interested listeners subscribe to changes without the subject knowing their concrete types. Local synchronous callbacks are often enough. This is not a durable event bus: a crashed process loses listeners and an in-process notification has no automatic redelivery guarantee.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Subject struct {\n\tlisteners map[int]func(int)\n\tnext      int\n}\n\nfunc (s *Subject) Subscribe(f func(int)) func() {\n\tid := s.next\n\ts.next++\n\ts.listeners[id] = f\n\treturn func() { delete(s.listeners, id) }\n}\nfunc (s *Subject) Notify(n int) {\n\tfor _, f := range s.listeners {\n\t\tf(n)\n\t}\n}\n\nfunc main() {\n\ts := Subject{listeners: make(map[int]func(int))}\n\ttotal := 0\n\tstop := s.Subscribe(func(n int) { total += n })\n\ts.Notify(3)\n\tstop()\n\ts.Notify(5)\n\tfmt.Println(total)\n}\n\n// Output:\n// 3\n","language":"go","title":"A complete Go example","walkthrough":"The subscription returns its own cleanup operation. After stop, a later notification has no effect on total. The example assumes a single owner, no reentrant map mutation and listeners whose order does not matter."},{"body":"Decide whether delivery is synchronous, ordered, droppable or buffered before introducing goroutines. Slow or panicking listeners can affect the subject. Retained callbacks can also retain large object graphs, so unsubscribe on the owner’s lifecycle boundary.","title":"Tradeoffs and the simpler alternative"},{"body":"Decide whether delivery is synchronous, ordered, droppable or buffered before introducing goroutines. Slow or panicking listeners can affect the subject. Retained callbacks can also retain large object graphs, so unsubscribe on the owner’s lifecycle boundary.","title":"Practical limits and cautions"}],"takeaway":"Needs explicit delivery and unsubscribe semantics. Decide whether delivery is synchronous, ordered, droppable or buffered before introducing goroutines. Slow or panicking listeners can affect the subject. Retained callbacks can also retain large object graphs, so unsubscribe on the owner’s lifecycle boundary.","title":"Observer: subscribe, notify and unsubscribe","unitID":"patterns-behavioral","wrongAnswers":["Is automatically a durable event bus","Can retain callbacks forever without lifecycle cost"]},{"conceptTag":"patterns.state","designGuide":{"cautions":["Persistence needs concurrency and retry rules","Separate state types can overcomplicate a small enum"],"cost":"Medium","family":"Behavioral pattern","flow":["Current state limits operations","Transition validates its precondition","New state changes allowed behavior"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":4}],"strengths":["Lifecycle rules are scattered across conditionals","Invalid transitions should be explicit errors"]},"hint":"Approve rejects a transition from Draft, then succeeds after Submit.","id":"patterns.state","introduction":"Represent legal transitions instead of scattered boolean combinations. State makes behavior depend on an explicit lifecycle state. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Persisted state machines need concurrency control, transition audit and idempotency.","objective":"Represent legal transitions instead of scattered boolean combinations.","question":"Which statement best describes State: behavior follows a valid lifecycle?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Restricts behavior to valid transitions from current state","reviewPrompt":"Lifecycle state","sections":[{"body":"State makes behavior depend on an explicit lifecycle state. A finite-state switch is often the simplest Go representation; separate state types help when each state owns substantial behavior. Write allowed transitions down so invalid combinations cannot quietly become normal.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\ntype Phase int\n\nconst (\n\tDraft Phase = iota\n\tSubmitted\n\tApproved\n)\n\ntype Review struct{ phase Phase }\n\nfunc (r *Review) Submit() error {\n\tif r.phase != Draft {\n\t\treturn errors.New(\"not a draft\")\n\t}\n\tr.phase = Submitted\n\treturn nil\n}\nfunc (r *Review) Approve() error {\n\tif r.phase != Submitted {\n\t\treturn errors.New(\"not submitted\")\n\t}\n\tr.phase = Approved\n\treturn nil\n}\n\nfunc main() {\n\tr := &Review{}\n\tfmt.Println(r.Approve())\n\tfmt.Println(r.Submit())\n\tfmt.Println(r.Approve())\n}\n\n// Output:\n// not submitted\n// <nil>\n// <nil>\n","language":"go","title":"A complete Go example","walkthrough":"Approve rejects a transition from Draft, then succeeds after Submit. One enum avoids contradictory submitted and approved booleans. This demonstrates the state-machine intent; the classic object State pattern delegates to separate state objects when their behaviors justify it."},{"body":"Persisted state machines need concurrency control, transition audit and idempotency. Do not create a type for each enum value when a short switch is clear. State varies because lifecycle changes; Strategy is typically selected as an interchangeable policy by a caller.","title":"Tradeoffs and the simpler alternative"},{"body":"Persisted state machines need concurrency control, transition audit and idempotency. Do not create a type for each enum value when a short switch is clear. State varies because lifecycle changes; Strategy is typically selected as an interchangeable policy by a caller.","title":"Practical limits and cautions"},{"body":"Approve rejects a transition from Draft, then succeeds after Submit. One enum avoids contradictory submitted and approved booleans. This demonstrates the state-machine intent; the classic object State pattern delegates to separate state objects when their behaviors justify it.","title":"How to read this example"}],"takeaway":"Restricts behavior to valid transitions from current state. Persisted state machines need concurrency control, transition audit and idempotency. Do not create a type for each enum value when a short switch is clear. State varies because lifecycle changes; Strategy is typically selected as an interchangeable policy by a caller.","title":"State: behavior follows a valid lifecycle","unitID":"patterns-behavioral","wrongAnswers":["Is the same as caller-selected Strategy","Multiple booleans prevent invalid combinations automatically"]},{"conceptTag":"patterns.template-method","designGuide":{"cautions":["Too many hooks obscure control flow","Real I/O requires error and cleanup contracts"],"cost":"Medium","family":"Behavioral pattern","flow":["Fixed workflow starts the operation","Supplied loading and formatting steps run","Workflow owns ordering and finalization"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":3}],"strengths":["Several workflows share a meaningful sequence","Only selected steps should vary"]},"hint":"Run fixes loading before formatting and owns the result prefix. Callers replace steps without changing this order. This is a composition-based Go adaptation of Template Method, rather than a claim that Go supports virtual method overrides.","id":"patterns.template-method","introduction":"Adapt the inheritance-based intent using composition in Go. Template Method defines the order of an algorithm while allowing selected steps to vary. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"If every step varies independently, a plain pipeline may be clearer than a framework with many hooks.","objective":"Adapt the inheritance-based intent using composition in Go.","question":"Which statement best describes Template Method: fixed workflow, supplied steps?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610"],"reviewAnswer":"Fixes algorithm order while supplying selected steps","reviewPrompt":"Template workflow","sections":[{"body":"Template Method defines the order of an algorithm while allowing selected steps to vary. Go does not override inherited methods, so explicit function dependencies can carry the same intent. The stable workflow should enforce the order and define what happens if a step fails.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype Workflow struct {\n\tLoad   func() string\n\tFormat func(string) string\n}\n\nfunc (w Workflow) Run() string {\n\traw := w.Load()\n\treturn \"result: \" + w.Format(raw)\n}\n\nfunc main() {\n\tw := Workflow{Load: func() string { return \"go\" }, Format: strings.ToUpper}\n\tfmt.Println(w.Run())\n}\n\n// Output:\n// result: GO\n","language":"go","title":"A complete Go example","walkthrough":"Run fixes loading before formatting and owns the result prefix. Callers replace steps without changing this order. This is a composition-based Go adaptation of Template Method, rather than a claim that Go supports virtual method overrides."},{"body":"If every step varies independently, a plain pipeline may be clearer than a framework with many hooks. Validate required callbacks at construction. Use error-returning steps and cleanup rules for real I/O, and avoid hooks that can silently skip mandatory security checks.","title":"Tradeoffs and the simpler alternative"},{"body":"If every step varies independently, a plain pipeline may be clearer than a framework with many hooks. Validate required callbacks at construction. Use error-returning steps and cleanup rules for real I/O, and avoid hooks that can silently skip mandatory security checks.","title":"Practical limits and cautions"}],"takeaway":"Fixes algorithm order while supplying selected steps. If every step varies independently, a plain pipeline may be clearer than a framework with many hooks. Validate required callbacks at construction. Use error-returning steps and cleanup rules for real I/O, and avoid hooks that can silently skip mandatory security checks.","title":"Template Method: fixed workflow, supplied steps","unitID":"patterns-behavioral","wrongAnswers":["Requires virtual method overrides in Go","Lets optional hooks bypass mandatory validation safely"]},{"conceptTag":"patterns.visitor","designGuide":{"cautions":["New node kinds affect every visitor","Large visitor interfaces increase maintenance"],"cost":"High","family":"Behavioral pattern","flow":["Node accepts an operation","Node dispatches by its concrete kind","Visitor implements traversal behavior"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":2}],"strengths":["Node kinds are stable and operations grow","A tree needs multiple independent passes"]},"hint":"Each node dispatches to its matching visitor method. Evaluate traverses child nodes to compute five without putting evaluation policy inside Add. A second visitor could count nodes while using the same node structure.","id":"patterns.visitor","introduction":"Understand the tradeoff between adding node types and adding operations. Visitor separates operations from a stable object structure using dispatch through the node type. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Adding a new visitor operation is straightforward, but adding a new node kind changes the Visitor interface and every implementation. This is the main tradeoff. Prefer a switch when the structure and operations are both small and local.","objective":"Understand the tradeoff between adding node types and adding operations.","question":"Which statement best describes Visitor: new operations over a stable set of nodes?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/go/ast#Visitor"],"reviewAnswer":"Adds operations easily but new node kinds affect visitors","reviewPrompt":"Visitor tradeoff","sections":[{"body":"Visitor separates operations from a stable object structure using dispatch through the node type. It is useful for syntax trees with many passes. In Go, a type switch may be simpler for a small local tree; classic Visitor becomes costly when node kinds change often.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Visitor interface {\n\tNumber(Number) int\n\tAdd(Add) int\n}\ntype Node interface{ Accept(Visitor) int }\ntype Number int\n\nfunc (n Number) Accept(v Visitor) int { return v.Number(n) }\n\ntype Add struct{ Left, Right Node }\n\nfunc (a Add) Accept(v Visitor) int { return v.Add(a) }\n\ntype Evaluate struct{}\n\nfunc (Evaluate) Number(n Number) int { return int(n) }\nfunc (v Evaluate) Add(a Add) int     { return a.Left.Accept(v) + a.Right.Accept(v) }\n\nfunc main() {\n\ttree := Add{Left: Number(2), Right: Number(3)}\n\tfmt.Println(tree.Accept(Evaluate{}))\n}\n\n// Output:\n// 5\n","language":"go","title":"A complete Go example","walkthrough":"Each node dispatches to its matching visitor method. Evaluate traverses child nodes to compute five without putting evaluation policy inside Add. A second visitor could count nodes while using the same node structure."},{"body":"Adding a new visitor operation is straightforward, but adding a new node kind changes the Visitor interface and every implementation. This is the main tradeoff. Prefer a switch when the structure and operations are both small and local.","title":"Tradeoffs and the simpler alternative"}],"takeaway":"Adds operations easily but new node kinds affect visitors. Adding a new visitor operation is straightforward, but adding a new node kind changes the Visitor interface and every implementation. This is the main tradeoff. Prefer a switch when the structure and operations are both small and local.","title":"Visitor: new operations over a stable set of nodes","unitID":"patterns-behavioral","wrongAnswers":["Makes new node kinds free to add everywhere","Is always simpler than a local type switch"]},{"conceptTag":"patterns.interpreter","designGuide":{"cautions":["Parser and diagnostics are additional work","Untrusted rules need depth and cost limits"],"cost":"High","family":"Behavioral pattern","flow":["Parse and validate a bounded grammar","Build expression nodes","Evaluate against an explicit environment"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":3},{"scenario":"Independent distributed services","score":2}],"strengths":["A small rule language changes as data","Rules need inspectable expression structure"]},"hint":"And evaluates two named conditions from an explicit environment and short-circuits on false.","id":"patterns.interpreter","introduction":"Model a grammar without treating arbitrary text as executable code. Interpreter represents a grammar with expression nodes and evaluates them against a context. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics.","objective":"Model a grammar without treating arbitrary text as executable code.","question":"Which statement best describes Interpreter: evaluate a deliberately small language?","references":["https://www.informit.com/store/design-patterns-elements-of-reusable-object-oriented-9780201633610","https://pkg.go.dev/go/parser"],"reviewAnswer":"Evaluates a defined expression language against a context","reviewPrompt":"Interpreter grammar","sections":[{"body":"Interpreter represents a grammar with expression nodes and evaluates them against a context. Small rule languages can make business conditions explicit. Parsing, validation and evaluation are separate responsibilities; do not confuse a tiny interpreter with safely running arbitrary user code.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Expr interface{ Eval(map[string]bool) bool }\ntype Name string\n\nfunc (n Name) Eval(env map[string]bool) bool { return env[string(n)] }\n\ntype And struct{ Left, Right Expr }\n\nfunc (a And) Eval(env map[string]bool) bool { return a.Left.Eval(env) && a.Right.Eval(env) }\n\nfunc main() {\n\trule := And{Left: Name(\"paid\"), Right: Name(\"inStock\")}\n\tfmt.Println(rule.Eval(map[string]bool{\"paid\": true, \"inStock\": false}))\n}\n\n// Output:\n// false\n","language":"go","title":"A complete Go example","walkthrough":"And evaluates two named conditions from an explicit environment and short-circuits on false. The program constructs an AST directly; it includes no parser. Unknown names currently mean false, which is a policy to validate rather than hide in a production rule system."},{"body":"Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics.","title":"Tradeoffs and the simpler alternative"},{"body":"And evaluates two named conditions from an explicit environment and short-circuits on false. The program constructs an AST directly; it includes no parser. Unknown names currently mean false, which is a policy to validate rather than hide in a production rule system.","title":"How to read this example"}],"takeaway":"Evaluates a defined expression language against a context. Keep a grammar small and bound input length, tree depth and evaluation cost for untrusted rules. A normal function is simpler when rules never change as data. Larger languages usually deserve a proper parser, type checker and diagnostics.","title":"Interpreter: evaluate a deliberately small language","unitID":"patterns-behavioral","wrongAnswers":["Safely executes any user code by default","Does not need limits on untrusted expression depth"]},{"conceptTag":"patterns.worker-pool","designGuide":{"cautions":["Early consumer exit needs cancellation","Queue capacity and worker count are separate limits"],"cost":"Medium","family":"Concurrent Go pattern","flow":["Producer feeds a bounded handoff","Fixed workers process independent jobs","Coordinator closes results after all workers exit"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":5}],"strengths":["Independent work has a concurrency budget","Downstream services must not be overloaded"]},"hint":"Two workers share one input channel; a coordinator closes results only after both have exited.","id":"patterns.worker-pool","introduction":"Control active work instead of starting one goroutine for every input. A worker pool bounds the number of operations in progress. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"This finite example drains every job.","objective":"Control active work instead of starting one goroutine for every input.","question":"Which statement best describes Worker pool: bound simultaneous work?","references":["https://go.dev/blog/pipelines","https://pkg.go.dev/sync#WaitGroup"],"reviewAnswer":"Limits active work independently of queue capacity","reviewPrompt":"Worker pool bound","sections":[{"body":"A worker pool bounds the number of operations in progress. Queue capacity is a separate limit on waiting work; neither should grow without a budget. Use a pool for independent jobs when the downstream capacity or memory cost is more important than spawning freedom.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nfunc Squares(jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {\n\tdefer wg.Done()\n\tfor n := range jobs {\n\t\tresults <- n * n\n\t}\n}\n\nfunc main() {\n\tjobs := make(chan int)\n\tresults := make(chan int)\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 2; i++ {\n\t\twg.Add(1)\n\t\tgo Squares(jobs, results, &wg)\n\t}\n\tgo func() {\n\t\tdefer close(jobs)\n\t\tfor _, n := range []int{1, 2, 3, 4} {\n\t\t\tjobs <- n\n\t\t}\n\t}()\n\tgo func() { wg.Wait(); close(results) }()\n\tsum := 0\n\tfor n := range results {\n\t\tsum += n\n\t}\n\tfmt.Println(sum)\n}\n\n// Output:\n// 30\n","language":"go","title":"A complete Go example","walkthrough":"Two workers share one input channel; a coordinator closes results only after both have exited. The receiver drains results concurrently with production, so unbuffered sends can progress. The sum is stable even though individual result order is not."},{"body":"This finite example drains every job. Production cancellation must reach job production and result sends so an early consumer exit cannot strand workers. Measure downstream limits and queue latency; more workers can overload a database rather than increase useful throughput.","title":"Tradeoffs and the simpler alternative"},{"body":"This finite example drains every job. Production cancellation must reach job production and result sends so an early consumer exit cannot strand workers. Measure downstream limits and queue latency; more workers can overload a database rather than increase useful throughput.","title":"Practical limits and cautions"},{"body":"Two workers share one input channel; a coordinator closes results only after both have exited. The receiver drains results concurrently with production, so unbuffered sends can progress. The sum is stable even though individual result order is not.","title":"How to read this example"}],"takeaway":"Limits active work independently of queue capacity. This finite example drains every job. Production cancellation must reach job production and result sends so an early consumer exit cannot strand workers. Measure downstream limits and queue latency; more workers can overload a database rather than increase useful throughput.","title":"Worker pool: bound simultaneous work","unitID":"patterns-go","wrongAnswers":["Guarantees completion order matches input order","Makes downstream capacity unlimited"]},{"conceptTag":"patterns.fan-in","designGuide":{"cautions":["Early exit can block forwarding goroutines","Ordered output needs extra identity and buffering"],"cost":"Medium","family":"Concurrent Go pattern","flow":["Several sources produce independently","Forwarders merge their values","Coordinator closes one shared output"],"ratings":[{"scenario":"Small tool or CLI","score":4},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":5}],"strengths":["Independent sources should overlap","One consumer should observe combined results"]},"hint":"Each forwarding goroutine signals completion, and only the coordinator closes out. main consumes the full merge, so every producer can finish. The sum is deterministic; the individual values can arrive in several valid orders.","id":"patterns.fan-in","introduction":"Coordinate multiple producers and one result stream. Fan-out spreads work across producers or workers; fan-in merges their results. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"When a consumer may stop early, use context-aware sends and ensure upstream producers also stop.","objective":"Coordinate multiple producers and one result stream.","question":"Which statement best describes Fan-out and fan-in: merge without assuming order?","references":["https://go.dev/blog/pipelines"],"reviewAnswer":"Closes merged output after every producer has finished","reviewPrompt":"Fan-in coordinator","sections":[{"body":"Fan-out spreads work across producers or workers; fan-in merges their results. The merger must know when all producers are done before closing the output. Arrival order generally differs from input order, so retain sequence numbers if the product needs ordered results.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nfunc Merge(inputs ...<-chan int) <-chan int {\n\tout := make(chan int)\n\tvar wg sync.WaitGroup\n\tfor _, input := range inputs {\n\t\twg.Add(1)\n\t\tgo func(ch <-chan int) {\n\t\t\tdefer wg.Done()\n\t\t\tfor n := range ch {\n\t\t\t\tout <- n\n\t\t\t}\n\t\t}(input)\n\t}\n\tgo func() { wg.Wait(); close(out) }()\n\treturn out\n}\n\nfunc main() {\n\ta, b := make(chan int, 2), make(chan int, 2)\n\ta <- 1\n\ta <- 2\n\tclose(a)\n\tb <- 3\n\tb <- 4\n\tclose(b)\n\tsum := 0\n\tfor n := range Merge(a, b) {\n\t\tsum += n\n\t}\n\tfmt.Println(sum)\n}\n\n// Output:\n// 10\n","language":"go","title":"A complete Go example","walkthrough":"Each forwarding goroutine signals completion, and only the coordinator closes out. main consumes the full merge, so every producer can finish. The sum is deterministic; the individual values can arrive in several valid orders."},{"body":"When a consumer may stop early, use context-aware sends and ensure upstream producers also stop. Merely buffering out to a guessed size hides the lifecycle problem. A simple sequential loop is easier when there is no parallel work to overlap.","title":"Tradeoffs and the simpler alternative"},{"body":"When a consumer may stop early, use context-aware sends and ensure upstream producers also stop. Merely buffering out to a guessed size hides the lifecycle problem. A simple sequential loop is easier when there is no parallel work to overlap.","title":"Practical limits and cautions"}],"takeaway":"Closes merged output after every producer has finished. When a consumer may stop early, use context-aware sends and ensure upstream producers also stop. Merely buffering out to a guessed size hides the lifecycle problem. A simple sequential loop is easier when there is no parallel work to overlap.","title":"Fan-out and fan-in: merge without assuming order","unitID":"patterns-go","wrongAnswers":["Lets each producer close the shared output","Guarantees a single deterministic arrival order"]},{"conceptTag":"patterns.cancellation","designGuide":{"cautions":["Cancellation is cooperative and can race with delivery","Unsupported blocking APIs need separate lifecycle design"],"cost":"Medium","family":"Concurrent Go pattern","flow":["Caller owns and cancels the context","Blocking handoff selects on Done","Producer closes output and the caller waits"],"ratings":[{"scenario":"Small tool or CLI","score":5},{"scenario":"Domain-rich application","score":5},{"scenario":"Independent distributed services","score":5}],"strengths":["A consumer can stop before a stream ends","Work needs deadlines or shutdown coordination"]},"hint":"The producer can leave a blocked send through ctx.Done and closes its own output on return.","id":"patterns.cancellation","introduction":"Make a producer stop when its consumer no longer needs results. Cancellation is a cooperative signal, not a forced goroutine kill. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Cancel on all completion paths to release timers and derived contexts.","objective":"Make a producer stop when its consumer no longer needs results.","question":"Which statement best describes Cancellation: propagate an exit path through every handoff?","references":["https://go.dev/blog/context","https://pkg.go.dev/context"],"reviewAnswer":"Requires blocking work to observe the cancellation signal","reviewPrompt":"Cooperative cancellation","sections":[{"body":"Cancellation is a cooperative signal, not a forced goroutine kill. Blocking channel operations must observe it, and the caller still needs a way to wait for completion. Carry context through the operation instead of storing request contexts in long-lived structs.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\nfunc Numbers(ctx context.Context) <-chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tdefer close(out)\n\t\tfor i := 1; ; i++ {\n\t\t\tselect {\n\t\t\tcase out <- i:\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc main() {\n\tctx, cancel := context.WithCancel(context.Background())\n\tout := Numbers(ctx)\n\tfirst := <-out\n\tcancel()\n\tfor range out {\n\t} // Wait until the producer closes its channel.\n\tfmt.Println(first, ctx.Err())\n}\n\n// Output:\n// 1 context canceled\n","language":"go","title":"A complete Go example","walkthrough":"The producer can leave a blocked send through ctx.Done and closes its own output on return. main cancels after the first value, then drains until completion. A racing send may already be ready when cancellation arrives, so cancellation does not promise zero additional values."},{"body":"Cancel on all completion paths to release timers and derived contexts. Do not replace completion waiting with time.Sleep. Real I/O adapters must support deadlines or cancellation themselves; passing a context does not interrupt an arbitrary blocking function.","title":"Tradeoffs and the simpler alternative"},{"body":"Cancel on all completion paths to release timers and derived contexts. Do not replace completion waiting with time.Sleep. Real I/O adapters must support deadlines or cancellation themselves; passing a context does not interrupt an arbitrary blocking function.","title":"Practical limits and cautions"},{"body":"The producer can leave a blocked send through ctx.Done and closes its own output on return. main cancels after the first value, then drains until completion. A racing send may already be ready when cancellation arrives, so cancellation does not promise zero additional values.","title":"How to read this example"}],"takeaway":"Requires blocking work to observe the cancellation signal. Cancel on all completion paths to release timers and derived contexts. Do not replace completion waiting with time.Sleep. Real I/O adapters must support deadlines or cancellation themselves; passing a context does not interrupt an arbitrary blocking function.","title":"Cancellation: propagate an exit path through every handoff","unitID":"patterns-go","wrongAnswers":["Forcibly kills every goroutine using the context","Guarantees no value can race with cancellation"]},{"conceptTag":"patterns.actor-owner","designGuide":{"cautions":["Synchronous replies can strand the owner","Mailbox capacity and overload need budgets"],"cost":"Medium","family":"Concurrent Go pattern","flow":["Caller sends an explicit request","One goroutine mutates its private state","Reply and done signals establish completion"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":4}],"strengths":["State transitions benefit from serial ownership","Shutdown and command order should be explicit"]},"hint":"Only Counter reads or writes total.","id":"patterns.actor-owner","introduction":"Use one goroutine to own mutable state and define request completion. An actor-like owner serializes access to its state through messages. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Serialize only what needs one owner; a busy owner can become a bottleneck.","objective":"Use one goroutine to own mutable state and define request completion.","question":"Which statement best describes Single owner: serialize state through messages?","references":["https://go.dev/doc/effective_go#sharing","https://pkg.go.dev/sync#Mutex"],"reviewAnswer":"Serializes mutation through one goroutine’s messages","reviewPrompt":"Single state owner","sections":[{"body":"An actor-like owner serializes access to its state through messages. This can make mutation and ordering explicit, but a Go channel does not automatically provide actor supervision, durability or remote messaging. A mutex is often simpler for a short shared-memory operation.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"fmt\"\n)\n\ntype Add struct {\n\tDelta int\n\tReply chan int\n}\n\nfunc Counter(requests <-chan Add, done chan<- struct{}) {\n\tdefer close(done)\n\ttotal := 0\n\tfor request := range requests {\n\t\ttotal += request.Delta\n\t\trequest.Reply <- total\n\t}\n}\n\nfunc main() {\n\trequests := make(chan Add)\n\tdone := make(chan struct{})\n\tgo Counter(requests, done)\n\treply := make(chan int)\n\trequests <- Add{Delta: 2, Reply: reply}\n\tfmt.Println(<-reply)\n\trequests <- Add{Delta: 3, Reply: reply}\n\tfmt.Println(<-reply)\n\tclose(requests)\n\t<-done\n}\n\n// Output:\n// 2\n// 5\n","language":"go","title":"A complete Go example","walkthrough":"Only Counter reads or writes total. Every request has a reply, so main knows when its change is applied, and done confirms shutdown. The caller must always receive the reply here; abandoned requests would require cancellation or a different response design."},{"body":"Serialize only what needs one owner; a busy owner can become a bottleneck. Define mailbox capacity and overload behavior, and avoid a cycle of owners synchronously waiting for each other. Channel ownership and a mutex are alternatives chosen by the lifecycle, not by fashion.","title":"Tradeoffs and the simpler alternative"},{"body":"Serialize only what needs one owner; a busy owner can become a bottleneck. Define mailbox capacity and overload behavior, and avoid a cycle of owners synchronously waiting for each other. Channel ownership and a mutex are alternatives chosen by the lifecycle, not by fashion.","title":"Practical limits and cautions"},{"body":"Only Counter reads or writes total. Every request has a reply, so main knows when its change is applied, and done confirms shutdown. The caller must always receive the reply here; abandoned requests would require cancellation or a different response design.","title":"How to read this example"}],"takeaway":"Serializes mutation through one goroutine’s messages. Serialize only what needs one owner; a busy owner can become a bottleneck. Define mailbox capacity and overload behavior, and avoid a cycle of owners synchronously waiting for each other. Channel ownership and a mutex are alternatives chosen by the lifecycle, not by fashion.","title":"Single owner: serialize state through messages","unitID":"patterns-go","wrongAnswers":["A channel adds durable actor supervision","Prevents all possible request deadlocks"]},{"conceptTag":"patterns.retry","designGuide":{"cautions":["Retries can multiply load and duplicate writes","Backoff must be capped and jittered in production"],"cost":"High","family":"Concurrent Go pattern","flow":["Classify a transient failure","Wait within a shared deadline","Retry the same logical idempotent operation"],"ratings":[{"scenario":"Small tool or CLI","score":3},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":5}],"strengths":["A transient failure can plausibly clear","The operation is safe to repeat within a budget"]},"hint":"The operation succeeds on attempt three; permanent errors would stop immediately.","id":"patterns.retry","introduction":"Retry transient failures within one deadline without multiplying side effects. A retry repeats an operation that may already have succeeded remotely. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"Keep attempt limits small and cap exponential delay before shifts can overflow.","objective":"Retry transient failures within one deadline without multiplying side effects.","question":"Which statement best describes Retry: bounded attempts and idempotent effects?","references":["https://learn.microsoft.com/en-us/azure/architecture/patterns/retry","https://pkg.go.dev/context"],"reviewAnswer":"Needs bounded attempts and an idempotent effect contract","reviewPrompt":"Retry safety","sections":[{"body":"A retry repeats an operation that may already have succeeded remotely. Limit attempts and total time, classify transient failures, and use an idempotency key for nontrivial writes. Backoff spaces attempts; jitter in production reduces synchronized retry bursts across clients.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar ErrTemporary = errors.New(\"temporary failure\")\n\nfunc Retry(ctx context.Context, attempts int, op func() error) error {\n\tif attempts <= 0 || attempts > 8 {\n\t\treturn errors.New(\"attempt limit must be 1 to 8\")\n\t}\n\tfor attempt := 0; attempt < attempts; attempt++ {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr := op()\n\t\tif err == nil || !errors.Is(err, ErrTemporary) || attempt == attempts-1 {\n\t\t\treturn err\n\t\t}\n\t\ttimer := time.NewTimer(time.Millisecond * time.Duration(1<<attempt))\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\ttimer.Stop()\n\t\t\treturn ctx.Err()\n\t\tcase <-timer.C:\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tdefer cancel()\n\tcalls := 0\n\terr := Retry(ctx, 3, func() error {\n\t\tcalls++\n\t\tif calls < 3 {\n\t\t\treturn ErrTemporary\n\t\t}\n\t\treturn nil\n\t})\n\tfmt.Println(calls, err)\n}\n\n// Output:\n// 3 <nil>\n","language":"go","title":"A complete Go example","walkthrough":"The operation succeeds on attempt three; permanent errors would stop immediately. The backoff wait observes cancellation. The supplied operation is local and immediate; a real remote operation should accept the same context so the deadline also reaches I/O."},{"body":"Keep attempt limits small and cap exponential delay before shifts can overflow. This mechanism omits jitter for deterministic teaching. Never blindly retry a payment without a durable idempotency contract, and avoid nested retry layers that multiply traffic during an outage.","title":"Tradeoffs and the simpler alternative"},{"body":"Keep attempt limits small and cap exponential delay before shifts can overflow. This mechanism omits jitter for deterministic teaching. Never blindly retry a payment without a durable idempotency contract, and avoid nested retry layers that multiply traffic during an outage.","title":"Practical limits and cautions"},{"body":"The operation succeeds on attempt three; permanent errors would stop immediately. The backoff wait observes cancellation. The supplied operation is local and immediate; a real remote operation should accept the same context so the deadline also reaches I/O.","title":"How to read this example"}],"takeaway":"Needs bounded attempts and an idempotent effect contract. Keep attempt limits small and cap exponential delay before shifts can overflow. This mechanism omits jitter for deterministic teaching. Never blindly retry a payment without a durable idempotency contract, and avoid nested retry layers that multiply traffic during an outage.","title":"Retry: bounded attempts and idempotent effects","unitID":"patterns-go","wrongAnswers":["Any timeout proves the remote write did not happen","Unlimited nested retries improve outage recovery"]},{"conceptTag":"patterns.circuit-breaker","designGuide":{"cautions":["Concurrent state and probe admission need protection","Failure classification and metrics affect usefulness"],"cost":"High","family":"Concurrent Go pattern","flow":["Closed state observes counted failures","Open state rejects calls for an interval","Half-open probe succeeds or reopens the circuit"],"ratings":[{"scenario":"Small tool or CLI","score":2},{"scenario":"Domain-rich application","score":4},{"scenario":"Independent distributed services","score":5}],"strengths":["A failing dependency consumes caller capacity","Recovery probes should be controlled"]},"hint":"After two failures, a third call is rejected without invoking fail.","id":"patterns.circuit-breaker","introduction":"Separate retry policy from failure isolation and a controlled recovery probe. A circuit breaker rejects calls after repeated failures, waits for a recovery interval, then permits a probe. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","nuance":"A concurrent implementation must lock state and admit only a bounded number of half-open probes.","objective":"Separate retry policy from failure isolation and a controlled recovery probe.","question":"Which statement best describes Circuit breaker: stop calls while a dependency recovers?","references":["https://learn.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker"],"reviewAnswer":"Rejects calls during an outage and probes for recovery","reviewPrompt":"Circuit breaker","sections":[{"body":"A circuit breaker rejects calls after repeated failures, waits for a recovery interval, then permits a probe. Closed, open and half-open describe the lifecycle. Unlike a retry, it reduces attempted work during a continuing outage; it does not prove the dependency is healthy.","title":"The design decision"},{"body":"Read this program from the entry point and follow the calls shown in the diagram. The output is included at the end so you can check the behavior without a compiler.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\nvar ErrOpen = errors.New(\"circuit open\")\n\ntype Breaker struct {\n\tfailures int\n\tuntil    time.Time\n}\n\nfunc (b *Breaker) Call(now time.Time, op func() error) error {\n\tif now.Before(b.until) {\n\t\treturn ErrOpen\n\t}\n\terr := op()\n\tif err == nil {\n\t\tb.failures = 0\n\t\tb.until = time.Time{}\n\t\treturn nil\n\t}\n\tb.failures++\n\tif b.failures >= 2 {\n\t\tb.until = now.Add(time.Second)\n\t}\n\treturn err\n}\n\nfunc main() {\n\tb := &Breaker{}\n\tnow := time.Unix(0, 0)\n\tcalls := 0\n\tfail := func() error { calls++; return errors.New(\"offline\") }\n\t_ = b.Call(now, fail)\n\t_ = b.Call(now, fail)\n\tfmt.Println(b.Call(now, fail), calls)\n\tfmt.Println(b.Call(now.Add(time.Second), func() error { return nil }))\n}\n\n// Output:\n// circuit open 2\n// <nil>\n","language":"go","title":"A complete Go example","walkthrough":"After two failures, a third call is rejected without invoking fail. Advancing the injected clock permits a successful recovery probe and resets the count. This is a single-owner teaching breaker; sequential execution permits one probe at a time implicitly."},{"body":"A concurrent implementation must lock state and admit only a bounded number of half-open probes. Classify which failures count, expose metrics, and avoid treating authorization errors as an outage. Prefer a proven library when failure windows and concurrent recovery become complex.","title":"Tradeoffs and the simpler alternative"},{"body":"A concurrent implementation must lock state and admit only a bounded number of half-open probes. Classify which failures count, expose metrics, and avoid treating authorization errors as an outage. Prefer a proven library when failure windows and concurrent recovery become complex.","title":"Practical limits and cautions"},{"body":"After two failures, a third call is rejected without invoking fail. Advancing the injected clock permits a successful recovery probe and resets the count. This is a single-owner teaching breaker; sequential execution permits one probe at a time implicitly.","title":"How to read this example"}],"takeaway":"Rejects calls during an outage and probes for recovery. A concurrent implementation must lock state and admit only a bounded number of half-open probes. Classify which failures count, expose metrics, and avoid treating authorization errors as an outage. Prefer a proven library when failure windows and concurrent recovery become complex.","title":"Circuit breaker: stop calls while a dependency recovers","unitID":"patterns-go","wrongAnswers":["Retries every rejected call immediately","Makes a failing dependency healthy automatically"]},{"conceptTag":"modules.identity-versions","designGuide":{"cautions":["A module versions a set of packages together. A package groups source in one directory; the repository name does not override its declared package identifier."],"cost":"Each extra module adds versioning, publishing and consumer-compatibility work; package boundaries inside one module are cheaper.","family":"Packages and production tooling","flow":["Repository","go.mod root","Package import","Versioned API"],"ratings":[],"strengths":["Resolve module roots, import paths, internal visibility and major-version suffixes."]},"hint":"Follow go.mod, then the subdirectory of the import.","id":"modules.identity-versions","introduction":"A repository, a module and a package can be three different boundaries. Trace the module path plus the package subdirectory before changing imports. A version suffix is part of the import identity; a folder name alone does not decide which source the compiler builds.","nuance":"A module versions a set of packages together. A package groups source in one directory; the repository name does not override its declared package identifier.","objective":"Resolve module roots, import paths, internal visibility and major-version suffixes.","question":"How do a module and a package relate?","references":["https://go.dev/doc/code","https://go.dev/doc/modules/major-version","https://go.dev/ref/mod#module-path"],"reviewAnswer":"One release can contain many directory packages","reviewPrompt":"Module and package","sections":[{"body":"Start from the working directory and inspect the active module and workspace. A nested go.mod starts another module and can make ./... skip source you expected to test. Package names need not match the final path element, although a clear correspondence usually makes code easier to read.","code":"go env GOMOD GOWORK\ngo list -f '{{.ImportPath}} => {{.Dir}}' ./...\ngo list -m","language":"bash","title":"Locate the source that is actually selected","walkthrough":"GOMOD identifies the active module file. The package listing maps each import to a real directory, so an unexpected checkout or nested module becomes visible before you edit source."},{"body":"For ordinary module-aware releases at v2 and above, /v2 is part of the module and import path. Updating a version number without updating the path is not a compatible major upgrade. Some legacy modules use +incompatible; do not copy that exception into a new module design.","code":"module example.com/catalog/v2\n\ngo 1.24.0","language":"text","title":"Major versions have distinct identities","walkthrough":"The root package is imported as example.com/catalog/v2; a subpackage is example.com/catalog/v2/search. The file illustrates path structure rather than asking you to fetch a nonexistent example module."},{"body":"An internal directory limits which importers may reach a package; it is not an authorization boundary for running code. A package import cycle fails before the program starts. Move a small consumer-owned contract or shared value to an acyclic boundary instead of solving a cycle with init side effects.","title":"Keep ownership inside one dependency direction"}],"takeaway":"Identify the active module and actual package directory first. Treat a new major import path as an API migration, and keep the dependency graph acyclic.","title":"A module is a release boundary; a package is a directory","unitID":"modules","wrongAnswers":["Every source file is a separately versioned module","The repository name always determines the package identifier"]},{"conceptTag":"modules.version-graph","designGuide":{"cautions":["The selected version for one module path must satisfy the graph’s minimum requirements. go.sum records content hashes, not a request for the newest version."],"cost":"A graph change can raise transitive versions; review and regression-test the selected delta instead of counting edited require lines.","family":"Packages and production tooling","flow":["Requirements","Selected graph","Reason for import","Test the delta"],"ratings":[],"strengths":["Read minimal version selection and investigate a transitive upgrade without guessing."]},"hint":"Separate a requirement edge from the selected build list.","id":"modules.version-graph","introduction":"A direct require is not a lock on every transitive dependency. Other requirements can raise the selected version of the same module path. Diagnose the graph first, then test the change that actually enters the build; repeatedly deleting go.sum does not explain an upgrade.","nuance":"The selected version for one module path must satisfy the graph’s minimum requirements. go.sum records content hashes, not a request for the newest version.","objective":"Read minimal version selection and investigate a transitive upgrade without guessing.","question":"Why can a transitive module be newer than your direct requirement?","references":["https://go.dev/doc/modules/managing-dependencies","https://go.dev/ref/mod#minimal-version-selection"],"reviewAnswer":"Other requirements can raise the selected minimum","reviewPrompt":"Selected dependency version","sections":[{"body":"go list -m all describes the selected module versions for this build. go mod graph shows requirement edges, while go mod why explains why a package or module is needed. These answer different questions; none proves that an upgraded API preserves your application behavior.","code":"go list -m all\ngo mod graph\ngo mod why -m golang.org/x/text\ngo list -m -u all","language":"bash","title":"Observe the build list","walkthrough":"Compare the requirement edges with the selected build list. A higher minimum from another dependency can explain a version that is newer than the one your own require line originally mentioned."},{"body":"Choose a reviewed version rather than upgrading everything during an outage. go get changes the dependency graph; go install package@version installs a command separately. Inspect go.mod and go.sum together and run affected integration tests, including the error and timeout behavior of upgraded clients.","code":"go get golang.org/x/text@v0.23.0\ngo mod tidy\ngit diff -- go.mod go.sum\ngo test ./...","language":"bash","title":"Change one dependency and review the result","walkthrough":"This is an example of a specific upgrade in a development checkout, not a recommendation that the illustrated version is current. Inspect the resulting graph and choose an appropriate supported version for your project."},{"body":"A replace can redirect source while leaving you unaware that CI builds something else. A retract signals a version that authors advise against; it does not erase an already selected dependency. Keep a minimal reproducer for an incompatible transitive update instead of treating a clean cache as a correctness test.","title":"Avoid false fixes"}],"takeaway":"Inspect the selected graph, explain the edge that raised a version, and validate the smallest dependency change with the application behaviors it affects.","title":"Explain the selected version before running go get","unitID":"modules","wrongAnswers":["go.sum always requests the newest release","The package name selects a random matching version"]},{"conceptTag":"modules.checksums-private","designGuide":{"cautions":["A checksum verifies the expected content of a version. It does not select that version, certify its behavior or establish that no vulnerability is known."],"cost":"Private fetches need reliable credentials and transport; retaining integrity checks makes failures easier to investigate.","family":"Packages and production tooling","flow":["Discover version","Fetch source","Verify content","Build selected graph"],"ratings":[],"strengths":["Diagnose downloads without leaking private paths or disabling integrity checks globally."]},"hint":"Integrity, authorization and dependency selection are different layers.","id":"modules.checksums-private","introduction":"A download failure may come from version discovery, credentials, a proxy, the checksum database or local cache integrity. Treat those as separate layers. A checksum records content identity; it neither proves the code is safe nor decides which version the dependency graph chooses.","nuance":"A checksum verifies the expected content of a version. It does not select that version, certify its behavior or establish that no vulnerability is known.","objective":"Diagnose downloads without leaking private paths or disabling integrity checks globally.","question":"What does a go.sum entry establish?","references":["https://go.dev/ref/mod#private-modules","https://go.dev/doc/modules/managing-dependencies"],"reviewAnswer":"Records verified content; it does not select versions","reviewPrompt":"go.sum","sections":[{"body":"Read configuration before changing it. Private module patterns affect how the Go command consults public services; they do not log you in to a private repository. Use the environment and credential mechanisms approved for that repository, and keep tokens out of module URLs and command history.","code":"go env GOPROXY GOPRIVATE GONOPROXY GONOSUMDB\ngo mod download -json\ngo mod verify","language":"bash","title":"Inspect effective settings","walkthrough":"The commands distinguish download provenance and local verification from compilation. Download JSON can contain private module paths, so inspect it locally and redact paths before sharing an incident report."},{"body":"GOPRIVATE is a pattern list for private module path prefixes. Configure a company-specific pattern in the environment of the developer shell and CI job. GOPROXY fallback with comma versus pipe has different failure behavior; choose deliberately instead of masking every proxy error with direct access.","code":"# Example only: replace the organization path.\nGOPRIVATE=github.com/example-company/* go mod download","language":"bash","title":"Scope private paths narrowly","walkthrough":"The assignment applies to this one command rather than silently altering every future shell. It still needs separately configured repository credentials and a network route to the source."},{"body":"A checksum mismatch deserves investigation of the module version, proxy and local files. Do not teach a build to accept changed content under an existing version. go.sum can include go.mod checksums for modules whose source is not used, and it may change after tidy without representing a new executable dependency.","title":"Keep integrity and availability separate"}],"takeaway":"Trace discovery, transport, credentials and checksums independently. Narrow private patterns and preserve integrity verification for public dependencies.","title":"Checksums, proxies and private modules solve different problems","unitID":"modules","wrongAnswers":["That the module has no vulnerabilities","That this module version is the newest available"]},{"conceptTag":"modules.workspace-replace","designGuide":{"cautions":["GOWORK=off removes the local workspace composition. That exposes missing published requirements and APIs that only worked through sibling modules or local replacements."],"cost":"Fast local iteration needs a separate isolated-consumer check to expose unpublished assumptions before release.","family":"Packages and production tooling","flow":["Local modules","Workspace resolution","Isolated consumer","Published artifact"],"ratings":[],"strengths":["Use go.work and replace for development while checking what an independent consumer builds."]},"hint":"Compare the local composition with a separate consumer.","id":"modules.workspace-replace","introduction":"A checkout can pass because go.work supplies a sibling module or replace points to a local directory that no consumer has. That success tests the local composition, not the published module. Keep a second path that exercises the version and files a real downstream user receives.","nuance":"GOWORK=off removes the local workspace composition. That exposes missing published requirements and APIs that only worked through sibling modules or local replacements.","objective":"Use go.work and replace for development while checking what an independent consumer builds.","question":"What risk can a build that passes only in the developer’s workspace hide?","references":["https://go.dev/doc/tutorial/workspaces","https://go.dev/blog/get-familiar-with-workspaces","https://go.dev/ref/mod#go-work-file"],"reviewAnswer":"Can depend on unpublished local replacements","reviewPrompt":"Workspace success","sections":[{"body":"Inspect the active workspace and replacements before comparing two machines. A local replacement changes source selection; a replace line in a dependency is not automatically inherited by its consumers. Avoid committing an absolute workstation path as a release dependency.","code":"go env GOWORK\ngo work edit -json\ngo list -m -json all","language":"bash","title":"See the workspace and overrides","walkthrough":"The workspace JSON lists participating module directories; the module listing shows replacements used by the build. Compare these facts before assuming a compiler or operating-system bug."},{"body":"Run checks with GOWORK=off from the module directory and build a small independent consumer using the intended release version. A workspace root with several modules is not equivalent to one module where ./... automatically promises to cover every sibling.","code":"GOWORK=off go mod tidy\nGOWORK=off go test ./...\nGOWORK=off go list -m all","language":"bash","title":"Verify the module on its own","walkthrough":"These commands deliberately ignore workspace composition. If the tests now fail, the difference is actionable: a missing requirement, an unpublished API or a dependency that only existed in the workspace."},{"body":"A coordinated local API change can make producer and consumer pass together while breaking older consumers. Release the producer compatibly, pin the consumer to the released version, then test that combination. Workspace convenience should not replace a compatibility matrix for separately released modules.","title":"Test migrations from both sides"}],"takeaway":"Use local overrides to iterate quickly, then turn them off to test the module and its published consumer contract independently.","title":"A local workspace can hide a broken release","unitID":"modules","wrongAnswers":["It disables all tests that touch the filesystem","It automatically publishes every workspace module"]},{"conceptTag":"modules.vendor-embed","designGuide":{"cautions":["Compilation does not automatically invoke go generate. Generation is an explicit workflow step whose tool version and output need their own checks."],"cost":"Vendor and generated assets increase repository and review volume; the payoff is explicit repeatable release inputs.","family":"Packages and production tooling","flow":["Source checkout","Selected files","Dependencies and assets","Release binary"],"ratings":[],"strengths":["Check the source and assets that a clean build actually receives."]},"hint":"Distinguish an explicit generation step from compilation.","id":"modules.vendor-embed","introduction":"A successful build in your checkout can depend on uncommitted generated files, platform-specific source or an asset missing from the release archive. Reproducibility concerns the whole input set: toolchain, selected modules, build constraints, generated files and embedded data.","nuance":"Compilation does not automatically invoke go generate. Generation is an explicit workflow step whose tool version and output need their own checks.","objective":"Check the source and assets that a clean build actually receives.","question":"How is go generate invoked in the module workflow?","references":["https://pkg.go.dev/cmd/go#hdr-Generate_Go_files_by_processing_source","https://pkg.go.dev/embed","https://go.dev/ref/mod#vendoring"],"reviewAnswer":"Runs only when explicitly requested","reviewPrompt":"go generate","sections":[{"body":"go list exposes which source and embedded files belong to the selected target. Build tags and GOOS/GOARCH can select different implementations. An import that works on your Mac may require cgo or assembly on another target; do not infer portability from a package download.","code":"go list -f '{{.GoFiles}} {{.IgnoredGoFiles}} {{.EmbedFiles}}' ./...\ngo list -deps ./...\ngo env GOOS GOARCH CGO_ENABLED","language":"bash","title":"Inspect the selected files and dependencies","walkthrough":"The file selection is concrete evidence for the current build configuration. Repeat it for the intended target and inspect dependency code before promising portability to a restricted runtime."},{"body":"Regenerate vendor after reviewing a dependency change and check it with the corresponding go.mod. Vendor mode deliberately uses that tree instead of treating a full module cache as the source of truth. Toolchain and platform differences still matter.","code":"go mod vendor\ngo test -mod=vendor ./...\ngo build -mod=vendor ./...","language":"bash","title":"Treat vendor as a derived dependency tree","walkthrough":"Run these in a development checkout or clean CI worktree. If module declarations and vendor metadata disagree, regenerate from the reviewed graph rather than hand-editing copied dependency source."},{"body":"go generate is explicit; go build does not run arbitrary generators for you. Check generated files or run a pinned generator in a defined build step. GopherForge currently does not preserve arbitrary non-Go embed assets while vendoring; learning native build commands here does not change that app limitation.","title":"Generated and embedded inputs are release inputs"}],"takeaway":"Build the clean release input set, not just the current working tree. Verify tags, generated files and assets, and keep vendor consistent with the reviewed graph.","title":"Reproduce the artifact: vendor, build tags and embedded files","unitID":"modules","wrongAnswers":["Before every compile of a generated package","Only when the module cache is empty"]},{"conceptTag":"modules.parallel-tests","designGuide":{"cautions":["Package test binaries and parallel subtests share downstream capacity. Isolate fixtures and bound their combined demand; the race detector does not size a database pool."],"cost":"Isolation requires disposable fixtures and cleanup; parallelism still spends shared database and machine capacity.","family":"Packages and production tooling","flow":["Isolated fixture","Bounded parallelism","Race evidence","Repeat failure"],"ratings":[],"strengths":["Find races, test caching mistakes and shared integration fixtures before scaling concurrency."]},"hint":"Count clients, test binaries and parallel subtests together.","id":"modules.parallel-tests","introduction":"A test can pass alone and fail when other packages or subtests run at the same time. Shared database names, environment variables, ports and mutable globals turn isolated test intent into interference. Give every test its own resources, and distinguish a data race from a wider coordination bug.","nuance":"Package test binaries and parallel subtests share downstream capacity. Isolate fixtures and bound their combined demand; the race detector does not size a database pool.","objective":"Find races, test caching mistakes and shared integration fixtures before scaling concurrency.","question":"What contract should parallel tests sharing a development database follow?","references":["https://pkg.go.dev/testing","https://go.dev/doc/articles/race_detector","https://go.dev/blog/subtests"],"reviewAnswer":"Need isolated fixtures and a shared capacity budget","reviewPrompt":"Parallel integration tests","sections":[{"body":"-p controls how many packages are built or tested concurrently; -parallel controls parallel tests within one test binary; GOMAXPROCS affects Go execution parallelism. Setting all three high can overwhelm a shared database even though each individual test uses only a few connections.","code":"go test -count=1 -shuffle=on ./...\ngo test -race -count=1 ./...\ngo test -p=2 -parallel=4 ./...","language":"bash","title":"Separate three kinds of parallelism","walkthrough":"A fresh run bypasses cached test results; shuffle exposes order dependence, and the race detector observes conflicting memory accesses on executed paths. None of these alone validates distributed database invariants."},{"body":"Use t.TempDir and t.Cleanup for filesystem state. Pick an OS-assigned listener port rather than a fixed global port. A test that mutates environment or process working directory must respect the testing package restrictions around parallel execution.","code":"func TestConfig(t *testing.T) {\n    dir := t.TempDir()\n    t.Setenv(\"APP_DATA\", dir)\n    // This test changes process environment; do not call t.Parallel.\n    got := os.Getenv(\"APP_DATA\")\n    if got != dir { t.Fatalf(\"APP_DATA = %q\", got) }\n}","language":"go","title":"Give temporary resources one owner","walkthrough":"The example is a test-file fragment importing testing and os. The test owns its directory and cleanup, and explicitly stays sequential because environment changes affect the whole process."},{"body":"Assert that work exits after cancellation and that database clients, rows, bodies and temporary servers are closed. A passing result with leaked goroutines can poison later tests or exhaust CI resources. Keep a failing shuffled seed or a deterministic reproducer rather than relying on repeated lucky retries.","title":"Test cancellation and resource release"}],"takeaway":"Make test ownership explicit, bound package and subtest parallelism separately, and use race detection as evidence on exercised paths rather than a proof of correctness.","title":"Parallel tests must own their mutable resources","unitID":"modules","wrongAnswers":["Increasing every pool to match the number of tests","Running with the race detector instead of managing resources"]},{"conceptTag":"modules.benchmark-load","designGuide":{"cautions":["A microbenchmark measures its own loop and inputs. It may omit network, pool wait, queue growth and overload failures that dominate a real service."],"cost":"Useful measurements require representative inputs, repeated runs and separate whole-service load evidence.","family":"Packages and production tooling","flow":["Question","Representative workload","Resource evidence","Latency distribution"],"ratings":[],"strengths":["Measure allocations, concurrency and tail latency without mistaking closed-loop throughput for service capacity."]},"hint":"Ask which delays and failures the benchmark does not include.","id":"modules.benchmark-load","introduction":"An ns/op number describes one workload in one process. A production incident may instead come from pool wait, queue growth, a slow downstream service or allocation pressure. Start with the question you need to answer and preserve the workload and environment alongside the measurement.","nuance":"A microbenchmark measures its own loop and inputs. It may omit network, pool wait, queue growth and overload failures that dominate a real service.","objective":"Measure allocations, concurrency and tail latency without mistaking closed-loop throughput for service capacity.","question":"What can a low ns/op result prove about a database-backed API?","references":["https://pkg.go.dev/testing#hdr-Benchmarks","https://go.dev/blog/profiling-go-programs","https://go.dev/doc/diagnostics"],"reviewAnswer":"Does not establish whole-service capacity","reviewPrompt":"Fast microbenchmark","sections":[{"body":"Select one benchmark, include allocation reporting and repeat it. Keep setup outside the timed section where that matches the production operation. Optimizing a string conversion says little about the complete HTTP-to-database request unless the conversion dominates that request.","code":"go test ./internal/codec -run='^$' -bench=BenchmarkEncode -benchmem -count=5\ngo test ./internal/codec -run='^$' -bench=BenchmarkEncode -cpu=1,2,4","language":"bash","title":"Repeat a focused microbenchmark","walkthrough":"Replace the package and benchmark with real ones. Repeated measurements expose noise; CPU variants reveal scaling effects, but they do not reproduce a network load generator or a remote database."},{"body":"RunParallel measures concurrent benchmark work using a closed loop. Retain observable work, avoid sharing an unsafe buffer, and define whether the benchmark measures hits, misses or both. Report failure rate, request sizes and queue limits for a service test instead of only a flattering average.","code":"var benchmarkBytes []byte\n\nfunc BenchmarkEncode(b *testing.B) {\n    input := []byte(\"catalog-item\")\n    b.ReportAllocs()\n    b.ResetTimer()\n    for i := 0; i < b.N; i++ {\n        out := append([]byte(nil), input...)\n        benchmarkBytes = out\n        if len(out) != len(input) { b.Fatal(\"short copy\") }\n    }\n}","language":"go","title":"Make parallel measurements honest","walkthrough":"This is a self-contained benchmark body importing testing. It intentionally includes the allocation and validates the result; use a representative payload before comparing implementations or drawing a capacity conclusion."},{"body":"At a steady incoming arrival rate, a saturated service can build a queue even while successful completions look fast. Observe p50/p95/p99 together with errors, active requests, pool checkout time and recovery after a burst. An unbounded queue delays failure instead of creating capacity.","title":"Look at the tail and overload response"}],"takeaway":"Use benchmarks to answer narrow code questions, then test the complete service with an explicit arrival rate, bounded queues and tail-latency/error measurements.","title":"A microbenchmark is not a capacity test","unitID":"modules","wrongAnswers":["That its p99 stays low at any request rate","That increasing goroutines will always increase throughput"]},{"conceptTag":"modules.profiles-contention","designGuide":{"cautions":["A blocked request can spend most of its time waiting while consuming little CPU. Inspect queue, pool and synchronization delays as well as execution samples."],"cost":"Profiles consume sampling overhead and need matching binaries, source revisions and a representative workload.","family":"Packages and production tooling","flow":["Latency symptom","CPU / allocation / wait","Profile and trace","One measured change"],"ratings":[],"strengths":["Use pprof and traces to investigate latency under load instead of increasing pools blindly."]},"hint":"Follow where requests spend time, including queues.","id":"modules.profiles-contention","introduction":"A high-latency request does not necessarily consume much CPU. It may be waiting on a mutex, scheduling, a network response or a connection pool. Capture evidence for the same workload and time window, and choose a profile that can explain the suspected delay.","nuance":"A blocked request can spend most of its time waiting while consuming little CPU. Inspect queue, pool and synchronization delays as well as execution samples.","objective":"Use pprof and traces to investigate latency under load instead of increasing pools blindly.","question":"Why can a slow service have a mostly idle CPU?","references":["https://go.dev/doc/diagnostics","https://pkg.go.dev/runtime/pprof","https://pkg.go.dev/runtime/trace"],"reviewAnswer":"May indicate waiting, not spare request capacity","reviewPrompt":"Low CPU with high latency","sections":[{"body":"CPU profiles show sampled execution time. Heap and allocation profiles answer different memory questions, so choose the sample type deliberately. Keep the test binary with its profiles and source revision; otherwise symbol names and comparisons can become misleading.","code":"go test ./internal/codec -run='^$' -bench=BenchmarkEncode -cpuprofile=cpu.out -memprofile=mem.out\ngo tool pprof -top cpu.out\ngo tool pprof -sample_index=alloc_space -top mem.out","language":"bash","title":"Capture a bounded benchmark profile","walkthrough":"The commands create local profile artifacts and show where time or allocated bytes accumulate in the measured benchmark. They do not show every blocked request or replace pool wait metrics from a real service."},{"body":"Execution traces provide a timeline of goroutines and runtime activity. Block and mutex profiles need suitable runtime sampling configuration; collecting zero samples is not evidence that a service never waits. Profiling itself can affect the workload, so compare with the uninstrumented baseline.","code":"go test ./internal/service -run TestBurst -trace=trace.out\ngo tool trace trace.out\ngo test ./internal/service -run TestBurst -blockprofile=block.out -mutexprofile=mutex.out","language":"bash","title":"Trace scheduling and explicit contention","walkthrough":"Replace TestBurst with a bounded representative test. Inspect overlap among waiting, CPU work and goroutine growth before changing concurrency or blaming the garbage collector."},{"body":"If pool checkout dominates, inspect request arrival rate and slow operations before raising pool limits. If allocation dominates, find retained objects and hot allocation sites. Expose production profiling only through an appropriately restricted diagnostic path because profiles can reveal application data and implementation details.","title":"Turn evidence into one falsifiable change"}],"takeaway":"Match the profile to the suspected bottleneck and compare one controlled change. CPU time, allocated bytes and waiting time are related but different measurements.","title":"Profile CPU, allocation and waiting as different bottlenecks","unitID":"modules","wrongAnswers":["Every slow request must consume one full core","The garbage collector always accounts for all request latency"]},{"conceptTag":"modules.build-capacity","designGuide":{"cautions":["The -p build flag limits concurrent package work in the toolchain. It does not impose a request, goroutine or database-connection limit on the compiled application."],"cost":"Lower package concurrency can increase build time while preventing memory exhaustion on a small worker.","family":"Packages and production tooling","flow":["Cold inputs","Parallel compiler jobs","Memory budget","Verified cached build"],"ratings":[],"strengths":["Separate compiler work, runtime goroutines and caches when CI or a small machine stalls."]},"hint":"The build process and the deployed service have separate budgets.","id":"modules.build-capacity","introduction":"A burst of parallel compilation can exhaust memory before the program you are testing even starts. Build-cache misses, many packages, cgo and simultaneous jobs change the working set. Read the exact failing phase instead of assuming every slowdown is a goroutine scheduling issue in application code.","nuance":"The -p build flag limits concurrent package work in the toolchain. It does not impose a request, goroutine or database-connection limit on the compiled application.","objective":"Separate compiler work, runtime goroutines and caches when CI or a small machine stalls.","question":"What does lowering go build -p primarily control?","references":["https://pkg.go.dev/cmd/go#hdr-Compile_packages_and_dependencies","https://go.dev/doc/gc-guide","https://go.dev/doc/toolchain"],"reviewAnswer":"Bounds concurrent package work, not request goroutines","reviewPrompt":"go build -p","sections":[{"body":"GOCACHE stores build artifacts while GOMODCACHE stores downloaded modules; these are different resources. A cache hit is useful only when the input and target match. Clearing both as the first troubleshooting step can amplify an outage by forcing every job to fetch and compile again.","code":"go env GOCACHE GOMODCACHE\ngo build -x -p=2 ./...\ngo test -p=2 ./...","language":"bash","title":"Observe rather than clear every cache","walkthrough":"The -x output reveals invoked tools and selected work. -p bounds build/test package parallelism, making it useful on constrained CI workers; it is separate from the deployed application’s connection and goroutine limits."},{"body":"Record the toolchain, module graph, target and build flags with the binary. go version -m inspects embedded build information. Repeat a clean dependency preparation in a fresh worktree or CI job when reproducibility is the question, instead of removing shared caches that other builds are using.","code":"go version\ngo env GOOS GOARCH CGO_ENABLED\ngo build -trimpath -o ./bin/app ./cmd/app\ngo version -m ./bin/app","language":"bash","title":"Identify the runtime and the artifact","walkthrough":"The example assumes a real cmd/app package in your checkout. -trimpath removes certain local path information; it is not a substitute for pinning inputs or proving that two independently built artifacts have identical bytes."},{"body":"A container memory limit, runtime GOMEMLIMIT, compiler package parallelism and application concurrency solve different problems. GOMEMLIMIT is a soft runtime target and does not cap all process or kernel memory. Change the limit indicated by evidence; increasing all limits can move the failure to the host.","title":"Set budgets at the correct layer"}],"takeaway":"Locate the failing phase and its resource owner. Bound build jobs separately from runtime work, and retain caches and build provenance deliberately.","title":"Build concurrency also has a memory budget","unitID":"modules","wrongAnswers":["The maximum number of HTTP requests in the built app","The database connection pool inside every package"]},{"conceptTag":"modules.tools-toolchain","designGuide":{"cautions":["A reviewed tool pin makes CI’s command input reproducible. It still needs maintenance; it neither fixes all dependencies to one version nor removes future security work."],"cost":"Pinned tools and compilers make output reproducible but add an explicit dependency-update responsibility.","family":"Packages and production tooling","flow":["go directive","Toolchain selection","Pinned tools","Repeatable output"],"ratings":[],"strengths":["Distinguish application dependencies, development commands and toolchain selection."]},"hint":"Reproducibility and ongoing maintenance both matter.","id":"modules.tools-toolchain","introduction":"The binary that formats, generates or analyzes your project is part of the workflow’s input. An unpinned command on PATH can silently change generated output or lint results. Keep the intended tool version and compiler selection explicit without confusing them with the libraries your application imports.","nuance":"A reviewed tool pin makes CI’s command input reproducible. It still needs maintenance; it neither fixes all dependencies to one version nor removes future security work.","objective":"Distinguish application dependencies, development commands and toolchain selection.","question":"Why pin development commands used by CI?","references":["https://go.dev/doc/toolchain","https://go.dev/doc/modules/managing-dependencies#tools","https://go.dev/doc/security/vuln/"],"reviewAnswer":"Makes a command version explicit, not permanently safe","reviewPrompt":"Tool pin","sections":[{"body":"The go directive states a module’s minimum Go version; a toolchain directive can suggest a toolchain for work on the main module. Depending on GOTOOLCHAIN, the go command may select or download another toolchain. CI should record its effective version instead of assuming PATH alone settles it.","code":"go version\ngo env GOTOOLCHAIN GOMOD GOWORK\ngo mod edit -json","language":"bash","title":"Read both go and toolchain directives","walkthrough":"Inspect the active module and its directives together. In a restricted or offline environment, automatic toolchain downloads may not be available; prepare the required supported compiler before the build."},{"body":"A versioned go install command builds the selected command independently of the current module’s application dependencies. Newer Go versions also support tracking tools in go.mod; use the mechanism supported by your project toolchain and keep CI invocation consistent.","code":"go install golang.org/x/vuln/cmd/govulncheck@v1.1.4\n# Run the installed command from the configured GOBIN/PATH.\ngovulncheck ./...","language":"bash","title":"Install one reviewed command version","walkthrough":"The version is an illustrative pin, not a claim that it is the latest release. Review and update tool pins deliberately; pinning avoids surprise changes but does not make an old tool permanently appropriate."},{"body":"Document which generated outputs belong in version control and which are produced during a clean build. Test the generated delta and avoid a generator that relies on an uncommitted local replacement. Tool updates deserve a separate diff so semantic application changes remain reviewable.","title":"Generators need the same discipline"}],"takeaway":"Record the effective compiler and reviewed tool versions. Keep generation reproducible and separate from ordinary library-version selection.","title":"Pin the compiler and the tools that generate your code","unitID":"modules","wrongAnswers":["To make every future security update unnecessary","To force all application libraries to the same version number"]},{"conceptTag":"modules.fuzz-vulnerability","designGuide":{"cautions":["A weak property can pass even when the parser is wrong; choose an oracle tied to the contract."],"cost":"Fuzzing spends a bounded compute budget; vulnerability findings require a maintained database and a reachable-code interpretation.","family":"Packages and production tooling","flow":["Boundary input","Fuzz property","Regression seed","Dependency finding"],"ratings":[],"strengths":["Combine fuzzing, regression seeds and govulncheck without treating one green tool as complete assurance."]},"hint":"State the input budget and the property actually asserted.","id":"modules.fuzz-vulnerability","introduction":"Normal tests often cover the examples you already understand. Parsers and protocol boundaries also receive truncated, oversized and surprising inputs. Fuzzing explores input behavior, while vulnerability analysis asks whether known vulnerable code is reachable; the two tools answer different questions.","nuance":"A weak property can pass even when the parser is wrong; choose an oracle tied to the contract.","objective":"Combine fuzzing, regression seeds and govulncheck without treating one green tool as complete assurance.","question":"How should you describe a bounded fuzz run that found no failure?","references":["https://go.dev/doc/tutorial/fuzz","https://go.dev/doc/security/vuln/","https://go.dev/security/fuzz/"],"reviewAnswer":"Report bounded evidence, not absence of every bug","reviewPrompt":"Green analysis tools","sections":[{"body":"A useful fuzz property can check round trips, bounded output, valid parsing or equivalent behavior between implementations. Avoid a property that merely repeats the implementation. Bound input size and work so one accidental huge allocation does not consume the entire test budget.","code":"func FuzzIntegerRoundTrip(f *testing.F) {\n    f.Add(\"12\")\n    f.Add(\"-1\")\n    f.Fuzz(func(t *testing.T, raw string) {\n        if len(raw) > 128 { t.Skip() }\n        n, err := strconv.Atoi(raw)\n        if err != nil { return }\n        again, err := strconv.Atoi(strconv.Itoa(n))\n        if err != nil || again != n { t.Fatal(\"integer round trip\") }\n    })\n}","language":"go","title":"Choose a property with a real oracle","walkthrough":"The fragment imports testing and strconv and asserts a defined parse/format/parse round trip for accepted integers. Rejected strings are allowed by the parser contract. For your own parser, choose an equally explicit invariant and retain meaningful failures as regression seeds."},{"body":"Run a bounded fuzz campaign in a development environment and commit the small failing seed that explains a fixed bug. Ordinary go test reruns seed corpus inputs without launching an open-ended fuzz search. Vulnerability checks should use a reviewed current database and tool in connected CI.","code":"go test ./internal/parser -fuzz=FuzzIntegerRoundTrip -fuzztime=20s\ngo test ./...\ngovulncheck ./...","language":"bash","title":"Give exploration and regression separate jobs","walkthrough":"The package path is illustrative and must contain the target. Fuzz time bounds the campaign; source-level vulnerability findings still need interpretation against the built artifact, call path and deployment configuration."},{"body":"A green scan only reports what the analyzer and its current vulnerability database know. It does not inspect every operational configuration or prove the absence of new vulnerabilities. A clean fuzz run means the explored inputs did not violate the asserted properties within that budget.","title":"Keep the conclusion proportional to the evidence"}],"takeaway":"Use a meaningful bounded input property, retain regression seeds and analyze dependency findings in context. No single tool replaces behavior and deployment review.","title":"Test unknown inputs and check reachable vulnerabilities","unitID":"modules","wrongAnswers":["All possible inputs have been exhaustively checked","Dependency security no longer needs maintenance"]},{"conceptTag":"modules.startup-ownership","designGuide":{"cautions":["The application component owns a shared client across requests, stops new work and drains existing work before closing it. Per-request pools multiply connection and startup costs."],"cost":"Explicit startup and drain ordering take code, but make connection ownership, failure and tests observable.","family":"Packages and production tooling","flow":["Load configuration","Construct shared client","Serve bounded work","Drain and close"],"ratings":[],"strengths":["Move fallible setup to an explicit owner and close shared resources after work drains."]},"hint":"Match resource lifetime to the component that uses it.","id":"modules.startup-ownership","introduction":"Imported packages initialize before main, and hidden setup can turn an import into a database connection, network wait or process-wide configuration decision. Make those dependencies visible at the composition root so startup, tests, retries and shutdown share a clear owner.","nuance":"The application component owns a shared client across requests, stops new work and drains existing work before closing it. Per-request pools multiply connection and startup costs.","objective":"Move fallible setup to an explicit owner and close shared resources after work drains.","question":"What lifecycle should a service-wide database client follow?","references":["https://go.dev/ref/spec#Package_initialization","https://pkg.go.dev/context","https://pkg.go.dev/net/http#Server.Shutdown"],"reviewAnswer":"Construct once; close after owned work drains","reviewPrompt":"Shared client lifetime","sections":[{"body":"A constructor can return an error and accept a caller-owned context; init cannot return an error to its caller. Build shared clients once, check readiness with a bounded operation, and inject them into handlers. Do not construct a new pool every time a request arrives.","code":"func run(ctx context.Context) error {\n    cfg, err := loadConfig()\n    if err != nil { return fmt.Errorf(\"config: %w\", err) }\n    store, err := openStore(ctx, cfg)\n    if err != nil { return fmt.Errorf(\"store: %w\", err) }\n    defer store.Close()\n    return serve(ctx, store)\n}","language":"go","title":"Keep fallible startup explicit","walkthrough":"This is an application-structure fragment: loadConfig, openStore and serve belong to the application. The ordering exposes error propagation and ownership, while real shutdown must let active handlers finish before the shared store closes."},{"body":"Look for init functions, package-level constructors, mutable registries and side-effect imports. Some registration is intentional; expensive or fallible runtime work needs a visible reason. An import cycle is a package-graph problem, not a request concurrency problem.","code":"go list -deps ./cmd/app\ngo list -f '{{.ImportPath}}: {{.Imports}}' ./internal/...\ngo test -count=1 ./...","language":"bash","title":"Audit hidden work in dependencies","walkthrough":"The commands show dependency paths and exercise a fresh test run. They do not inspect hidden effects automatically; combine the graph with reading constructors and initialization code at the boundaries you own."},{"body":"A readiness check should answer whether this instance can serve useful work, not hammer every dependency on every health probe. Stop new work, drain in-flight requests within a deadline, then close shared clients. Use a new bounded cleanup context when the request context is already canceled.","title":"Budget readiness and shutdown"}],"takeaway":"Give fallible setup, request work and cleanup explicit owners. Reuse shared clients, preserve deadlines and test startup failure and shutdown ordering.","title":"Package initialization is not a request-time connection factory","unitID":"modules","wrongAnswers":["Each handler creates and forgets its own pool","Every imported package silently creates one in init"]},{"conceptTag":"datastores.mongo-client","designGuide":{"cautions":["Connect configures a client; a bounded Ping separately tests current server readiness. Neither promises that future network operations cannot fail or time out."],"cost":"One shared client owns pools and topology monitoring; each additional service instance multiplies that connection demand.","family":"Around Go: data stores","flow":["One shared client","Bounded readiness","Typed operation","Bounded cleanup"],"ratings":[],"strengths":["Connect with the Go v2 driver and separate construction, readiness, request work and cleanup."]},"hint":"Construction and a bounded server operation are separate events.","id":"datastores.mongo-client","introduction":"MongoDB stores BSON documents and the Go driver manages discovery and pools for the deployment. A collection handle is not a new physical connection. Reuse a client across requests, model the fields the application owns, and keep network setup outside request-time package initialization.","nuance":"Connect configures a client; a bounded Ping separately tests current server readiness. Neither promises that future network operations cannot fail or time out.","objective":"Connect with the Go v2 driver and separate construction, readiness, request work and cleanup.","question":"What does a successful mongo.Connect call establish?","references":["https://www.mongodb.com/docs/drivers/go/current/connect/","https://www.mongodb.com/docs/drivers/go/current/context/","https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo"],"reviewAnswer":"Does not alone prove server readiness","reviewPrompt":"mongo.Connect succeeds","sections":[{"body":"The example uses go.mongodb.org/mongo-driver/v2, with v2.3.1 as a reproducible example pin. Connect constructs the client; a successful Ping is separate evidence that a server is reachable. In a native development checkout, obtain the URI from configuration and use the deployment’s required authentication and TLS.","code":"client, err := mongo.Connect(options.Client().ApplyURI(uri).SetMaxPoolSize(16))\nif err != nil { return err }\nprobe, cancel := context.WithTimeout(ctx, 2*time.Second)\nerr = client.Ping(probe, readpref.Primary())\ncancel()\nif err != nil {\n    cleanup, stop := context.WithTimeout(context.Background(), time.Second)\n    defer stop()\n    _ = client.Disconnect(cleanup)\n    return err\n}","language":"go","title":"Construct the client and probe readiness","walkthrough":"The fragment belongs to a startup function returning error and imports context, time, mongo, mongo/options and mongo/readpref from the v2 driver. The pool size is illustrative, not a production sizing recommendation."},{"body":"Use BSON tags and explicit field types instead of letting every layer pass an unstructured map. Validate external input before constructing a query. ErrNoDocuments is an expected absence case when the contract allows it; it is different from a timeout, authorization failure or decode error.","code":"type Note struct {\n    ID bson.ObjectID `bson:\"_id,omitempty\"`\n    Tenant string `bson:\"tenant\"`\n    Body string `bson:\"body\"`\n}\nvar note Note\nerr := notes.FindOne(ctx, bson.D{{Key: \"tenant\", Value: tenant}, {Key: \"_id\", Value: id}}).Decode(&note)\nif errors.Is(err, mongo.ErrNoDocuments) { return ErrNotFound }\nif err != nil { return fmt.Errorf(\"load note: %w\", err) }","language":"go","title":"Decode into a deliberate schema","walkthrough":"notes is a collection from the shared client; tenant and id come from validated application inputs. The application defines ErrNotFound. An omitted tenant predicate could become a data-isolation bug even if the database query is fast."},{"body":"Every request operation should inherit a bounded caller context. Startup probes and final Disconnect need their own lifetimes; do not reuse an already canceled request context for cleanup. These native service snippets are reading material: GopherForge does not add remote MongoDB sockets to its WASI execution sandbox.","title":"Use separate lifetimes"}],"takeaway":"Reuse a configured v2 client, prove readiness separately, decode explicit BSON models and distinguish absence from infrastructure failures.","title":"MongoDB: one client, explicit deadlines and typed documents","unitID":"datastores","wrongAnswers":["Every future operation will complete within its deadline","A new client must be created for each collection operation"]},{"conceptTag":"datastores.mongo-indexes","designGuide":{"cautions":["The useful plan depends on filter, sort, selectivity and index shape. Explain measures examined work; a client pool setting does not guarantee index use."],"cost":"Each index consumes storage, memory and write maintenance; keep it only when the measured access pattern earns that cost.","family":"Around Go: data stores","flow":["Filter and sort","Candidate index","Explain evidence","Measured write cost"],"ratings":[],"strengths":["Use explain evidence, tenant predicates and stable pagination rather than adding indexes blindly."]},"hint":"Compare work examined with useful rows returned.","id":"datastores.mongo-indexes","introduction":"A query that is fast with ten documents may scan a large collection after real traffic arrives. Shape the filter, sort and returned fields around an actual use case, then inspect the execution plan and the documents examined. Indexes improve selected reads while adding write, memory and maintenance cost.","nuance":"The useful plan depends on filter, sort, selectivity and index shape. Explain measures examined work; a client pool setting does not guarantee index use.","objective":"Use explain evidence, tenant predicates and stable pagination rather than adding indexes blindly.","question":"Which trade-off should be evaluated when adding a MongoDB index?","references":["https://www.mongodb.com/docs/manual/core/indexes/index-types/index-compound/","https://www.mongodb.com/docs/manual/tutorial/analyze-query-plan/","https://www.mongodb.com/docs/manual/reference/method/cursor.skip/"],"reviewAnswer":"Trades selected read work for storage and write cost","reviewPrompt":"An added index","sections":[{"body":"In an isolated development database, consider a tenant’s newest notes. A compound index starts with tenant equality and then the chosen sort keys. Keep the tie-breaker consistent with pagination so equal timestamps do not create unstable page boundaries.","code":"db.notes.createIndex({tenant: 1, createdAt: -1, _id: -1})\ndb.notes.find({tenant: \"demo\"}, {body: 1, createdAt: 1})\n  .sort({createdAt: -1, _id: -1}).limit(20).explain(\"executionStats\")","language":"javascript","title":"Create an index for one access pattern","walkthrough":"These mongosh commands assume demo documents in a development database. Compare nReturned, totalKeysExamined and totalDocsExamined and inspect the winning plan; explain executionStats runs the query and can itself add load."},{"body":"For descending pagination, continue before the last (createdAt, _id) pair instead of repeatedly skipping an ever-growing number of earlier results. Match the sort and predicate with the index, and define what happens when documents change between pages.","code":"db.notes.find({tenant: \"demo\", $or: [\n  {createdAt: {$lt: ISODate(\"2026-10-01T00:00:00Z\")}},\n  {createdAt: ISODate(\"2026-10-01T00:00:00Z\"),\n   _id: {$lt: ObjectId(\"650000000000000000000001\")}}\n]}).sort({createdAt: -1, _id: -1}).limit(20)","language":"javascript","title":"Use a stable continuation predicate","walkthrough":"The timestamp and ObjectId are example continuation values, not an offset. New writes may change a live listing; a stable ordering is not automatically a snapshot of the collection across multiple requests."},{"body":"A large limit, broad regex, missing tenant condition or incompatible sort can overwhelm a previously adequate pool. Index order, multikey behavior and collation affect usable plans. Measure representative data distribution and write latency before retaining another index; hints can hide a modeling error.","title":"Verify selectivity and write cost"}],"takeaway":"Design filter, sort, projection and continuation together, verify examined work with explain, and account for index maintenance on every write.","title":"MongoDB: design the query and its compound index together","unitID":"datastores","wrongAnswers":["Any index guarantees constant-time queries","Pool size determines whether every query uses its index"]},{"conceptTag":"datastores.mongo-atomic","designGuide":{"cautions":["No driver error does not mean the predicate matched. Check MatchedCount and handle an absent or stale-version document; one-document atomicity does not cover every business invariant."],"cost":"Version conflicts become visible application outcomes; the caller needs retry, merge or user-facing conflict behavior.","family":"Around Go: data stores","flow":["Expected version","Conditional update","Matched result","Conflict or success"],"ratings":[],"strengths":["Prevent lost updates with atomic operators and optimistic version checks."]},"hint":"No driver error does not imply that the predicate matched.","id":"datastores.mongo-atomic","introduction":"Reading a document, changing a field in Go and writing it back leaves a window for another request to change the same value. Memory race detection cannot find that distributed lost update. Express the allowed transition in the database predicate and inspect whether the write actually matched.","nuance":"No driver error does not mean the predicate matched. Check MatchedCount and handle an absent or stale-version document; one-document atomicity does not cover every business invariant.","objective":"Prevent lost updates with atomic operators and optimistic version checks.","question":"How should a version-checked MongoDB update that matches no document be treated?","references":["https://www.mongodb.com/docs/manual/core/write-operations-atomicity/","https://www.mongodb.com/docs/manual/core/index-unique/","https://www.mongodb.com/docs/drivers/go/current/crud/update/"],"reviewAnswer":"Is an outcome to handle, not automatic success","reviewPrompt":"Zero matched updates","sections":[{"body":"Use an atomic field operator when it expresses the intended operation. A client-side read followed by replacement can lose a concurrent edit or erase fields the caller never loaded. Include ownership predicates such as the tenant in the write, not only in the earlier read.","code":"filter := bson.D{{Key: \"_id\", Value: id}, {Key: \"tenant\", Value: tenant}, {Key: \"version\", Value: expected}}\nupdate := bson.D{\n    {Key: \"$set\", Value: bson.D{{Key: \"body\", Value: body}}},\n    {Key: \"$inc\", Value: bson.D{{Key: \"version\", Value: 1}}},\n}\nresult, err := notes.UpdateOne(ctx, filter, update)\nif err != nil { return err }\nif result.MatchedCount == 0 { return ErrConflict }","language":"go","title":"Update fields without replacing unrelated state","walkthrough":"This fragment assumes the shared v2 driver collection and application variables. A zero match can mean stale version or absence; map that to the application contract rather than reporting an unconditional successful save."},{"body":"A preliminary find cannot guarantee that another request will not insert the same business key. Define a unique index for that invariant and handle duplicate-key errors deliberately. In multi-tenant systems, decide whether uniqueness is global or scoped to a tenant.","code":"db.notes.createIndex({tenant: 1, externalID: 1}, {unique: true})\ndb.notes.updateOne(\n  {tenant: \"demo\", externalID: \"invoice-42\"},\n  {$setOnInsert: {body: \"first value\", version: 1}},\n  {upsert: true}\n)","language":"javascript","title":"Enforce uniqueness where concurrent writers meet","walkthrough":"The example is a development upsert keyed by a stable external identifier. Review existing duplicate data before adding the unique index; deployment of an invariant is itself a migration that can fail."},{"body":"One atomic update does not make a two-document business operation atomic. Prefer a document model that contains the invariant when practical, or use a transaction with a clear cost and retry policy. Avoid promising exactly-once business effects just because the driver can retry an eligible write.","title":"Single-document atomicity has a boundary"}],"takeaway":"Use conditional atomic writes and database-enforced uniqueness for concurrent invariants. Treat unmatched writes and duplicate keys as meaningful outcomes.","title":"MongoDB: put the invariant in the write predicate","unitID":"datastores","wrongAnswers":["Only whether the preceding read found a document","Whether the Go race detector reported shared memory"]},{"conceptTag":"datastores.mongo-transactions","designGuide":{"cautions":["The driver can rerun the transaction callback. MongoDB cannot roll back an external payment or email, so make database work repeatable and deliver external effects through an idempotent boundary."],"cost":"Transactions add coordination and contention; the outbox adds durable records, delivery workers and duplicate handling.","family":"Around Go: data stores","flow":["Business operation ID","Transaction callback","Commit outcome","Outbox delivery"],"ratings":[],"strengths":["Choose transaction boundaries, concerns and idempotency for ambiguous failures."]},"hint":"The database cannot undo an effect in another system.","id":"datastores.mongo-transactions","introduction":"A transaction can protect a multi-document invariant, but it adds coordination and can retry work. A callback that charges a card or sends email while updating documents can repeat an external effect. Keep the database transition inside the transaction and move external delivery behind an explicit durable boundary.","nuance":"The driver can rerun the transaction callback. MongoDB cannot roll back an external payment or email, so make database work repeatable and deliver external effects through an idempotent boundary.","objective":"Choose transaction boundaries, concerns and idempotency for ambiguous failures.","question":"What can an automatic WithTransaction retry do to the application callback?","references":["https://www.mongodb.com/docs/drivers/go/current/crud/transactions/","https://www.mongodb.com/docs/manual/core/transactions-production-consideration/","https://www.mongodb.com/docs/manual/reference/write-concern/"],"reviewAnswer":"Can repeat its application-side code","reviewPrompt":"Transaction callback retries","sections":[{"body":"The Go v2 driver’s WithTransaction callback receives the context that operations in the transaction must use. Do not share a session concurrently across goroutines or start parallel operations inside one transaction. A replica-set or supported sharded deployment is required; a standalone local server is not equivalent.","code":"session, err := client.StartSession()\nif err != nil { return err }\ndefer func() {\n    cleanup, stop := context.WithTimeout(context.Background(), time.Second)\n    defer stop()\n    session.EndSession(cleanup)\n}()\n_, err = session.WithTransaction(ctx, func(tx context.Context) (any, error) {\n    if _, err := orders.InsertOne(tx, order); err != nil { return nil, err }\n    return outbox.InsertOne(tx, event)\n})\nreturn err","language":"go","title":"Keep session work sequential and owned","walkthrough":"The application constructs order and event with stable operation identifiers and uses collections from the same shared client. The callback contains database work only; the outbox consumer sends the external notification after commit."},{"body":"Read concern, write concern and read preference affect visibility and acknowledgment. A timeout or lost response can leave the caller unsure whether a commit happened. Reconcile using the durable operation ID rather than assuming every error means nothing changed.","code":"db.orders.createIndex({operationID: 1}, {unique: true})\ndb.outbox.createIndex({eventID: 1}, {unique: true})\ndb.orders.findOne({operationID: \"checkout-demo-42\"})","language":"javascript","title":"Define what committed means for this operation","walkthrough":"These development commands illustrate the durable keys used for reconciliation. Unique identifiers do not on their own deliver an external effect exactly once; the receiver and delivery process also need idempotency."},{"body":"Inject a transient transaction failure, an ambiguous commit response and a consumer crash after sending but before marking delivery. Verify the resulting invariant and duplicate handling. Short transactions reduce contention; do not perform slow HTTP calls or user interaction while holding a transaction open.","title":"Test the failure windows"}],"takeaway":"A retryable transaction callback should contain repeatable database work. Use durable operation IDs and an outbox when the business action crosses systems.","title":"MongoDB transactions: retry database work, not external effects","unitID":"datastores","wrongAnswers":["MongoDB automatically rolls back every remote HTTP service","A shared session makes all goroutines globally sequential"]},{"conceptTag":"datastores.mongo-cursors","designGuide":{"cautions":["Streaming only stays memory-bounded when the query and downstream consumer both have explicit limits."],"cost":"Bounded iteration reduces retained memory but requires cursor ownership, cancellation and downstream backpressure.","family":"Around Go: data stores","flow":["Bounded query","Batch from server","Process one document","Check and close"],"ratings":[],"strengths":["Avoid loading an unbounded collection into application memory."]},"hint":"The consumer may still retain every batch.","id":"datastores.mongo-cursors","introduction":"A cursor lets an application consume a result in batches; it is not permission to read the entire database without a budget. The query, projection, batch size, total limit and request deadline jointly determine network work and application memory. Check errors after iteration, not only when opening the cursor.","nuance":"Streaming only stays memory-bounded when the query and downstream consumer both have explicit limits.","objective":"Avoid loading an unbounded collection into application memory.","question":"Why is a small batch size insufficient protection against memory growth?","references":["https://www.mongodb.com/docs/drivers/go/current/crud/query/cursor/","https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo#Cursor","https://www.mongodb.com/docs/drivers/go/current/crud/query/specify-return-documents/"],"reviewAnswer":"Controls batches, not the total result limit","reviewPrompt":"Cursor batch size","sections":[{"body":"The v2 cursor’s Next can fail after some documents have already been decoded. Close the cursor on every path and propagate decode and cursor errors. A batch size controls transfer grouping; a total limit controls how much useful work the request is willing to perform.","code":"cursor, err := notes.Find(ctx, filter, options.Find().SetLimit(100).SetBatchSize(25))\nif err != nil { return err }\ndefer func() {\n    cleanup, stop := context.WithTimeout(context.Background(), time.Second)\n    defer stop()\n    _ = cursor.Close(cleanup)\n}()\nfor cursor.Next(ctx) {\n    var note Note\n    if err := cursor.Decode(&note); err != nil { return err }\n    if err := consume(note); err != nil { return err }\n}\nreturn cursor.Err()","language":"go","title":"Iterate with a deadline and a total limit","walkthrough":"The fragment assumes a bounded ctx, the application’s Note model and a consumer that does not retain every document. Cleanup gets a fresh bounded context so a canceled request does not prevent the cursor-close attempt."},{"body":"For a list view, return a small subset rather than large embedded payloads. Calling All on an unbounded cursor can materialize the whole result and exhaust memory. BatchSize does not impose a total row limit or protect you if consume appends every document to a slice.","code":"db.notes.find({tenant: \"demo\"}, {body: 1, createdAt: 1})\n  .sort({createdAt: -1, _id: -1}).limit(100).batchSize(25)","language":"javascript","title":"Project only what this path needs","walkthrough":"The development shell query caps the result independently of the batch size. Keep a supporting index for the actual filter and sort and measure response bytes as well as document count."},{"body":"If documents are sent to worker goroutines, use a bounded channel and cancellation path. Otherwise a streaming query can simply move the unbounded queue into Go memory. Do not concurrently use one cursor from multiple goroutines; give iteration one owner and distribute decoded values deliberately.","title":"Own downstream backpressure"}],"takeaway":"Bound total work separately from batch grouping, inspect cursor.Err, close on every path, and keep downstream buffering bounded.","title":"MongoDB cursors: bound the result and close the stream","unitID":"datastores","wrongAnswers":["It makes the server ignore all query predicates","It automatically discards every decoded document"]},{"conceptTag":"datastores.mongo-load","designGuide":{"cautions":["Client pool capacity, waiting goroutines and total deployment connections are different quantities."],"cost":"Admission limits trade immediate overload rejection for bounded waiting; tuning requires client and server telemetry together.","family":"Around Go: data stores","flow":["Admission budget","Pool checkout","Indexed operation","Latency and failure evidence"],"ratings":[],"strengths":["Separate server selection, pool checkout, query time and application queueing."]},"hint":"Find the stage that consumes the operation deadline.","id":"datastores.mongo-load","introduction":"When every operation slows down, a larger pool can multiply pressure on the same database. Investigate where the deadline is spent: waiting in the application, selecting a server, checking out a connection, creating a socket or executing a query. Count all application instances and topology servers in the capacity model.","nuance":"Client pool capacity, waiting goroutines and total deployment connections are different quantities.","objective":"Separate server selection, pool checkout, query time and application queueing.","question":"What risk does a larger connection pool carry when the database is already the bottleneck?","references":["https://www.mongodb.com/docs/drivers/go/current/connect/connection-options/connection-pools/","https://www.mongodb.com/docs/drivers/go/current/context/","https://www.mongodb.com/docs/manual/reference/command/serverStatus/"],"reviewAnswer":"Can increase pressure without reducing the bottleneck","reviewPrompt":"Larger connection pool","sections":[{"body":"A pool is associated with a server in the topology; monitoring connections add to the total. MaxPoolSize limits active pool capacity, not the number of goroutines allowed to wait. Give operations a deadline and bound application admission so overload does not become an invisible growing queue.","code":"opts := options.Client().ApplyURI(uri).\n    SetMaxPoolSize(16).SetMaxConnecting(2).\n    SetMaxConnIdleTime(60*time.Second).SetTimeout(2*time.Second)\nclient, err := mongo.Connect(opts)\nif err != nil { return err }","language":"go","title":"Reuse a bounded shared client","walkthrough":"These are illustrative v2 settings for a small service, not universal recommendations. Estimate total connections across all instances and topology members and compare checkout wait with query duration before changing the cap."},{"body":"In a development environment, inspect operation behavior with an explain plan and server metrics. Add client-side pool and command monitoring at the application boundary; avoid logging credentials, raw documents or sensitive filter values in telemetry.","code":"db.notes.find({tenant: \"demo\"}).limit(20).explain(\"executionStats\")\ndb.serverStatus().connections\ndb.serverStatus().opcounters","language":"javascript","title":"Use evidence from both client and database","walkthrough":"Availability of server metrics depends on deployment permissions and product. Correlate a time window of pool checkout wait, request errors and examined documents; a lifetime counter alone cannot explain current tail latency."},{"body":"One overall deadline should cover queueing and attempts. Restrict retryable work and test server failover, pool saturation and slow-query recovery. Separate a deliberately slow bulk operation from latency-sensitive traffic when their budgets differ, and prefer fixing an inefficient query to adding thousands of waiting goroutines.","title":"Recover without a retry storm"}],"takeaway":"Bound admission and waiting as well as sockets, then tune using correlated request, pool and query evidence. More connections do not repair an overloaded database.","title":"MongoDB under load: budget waiting before enlarging the pool","unitID":"datastores","wrongAnswers":["Adding an unbounded goroutine for every queued operation","Retrying every failed write forever"]},{"conceptTag":"datastores.redis-client","designGuide":{"cautions":["redis.Nil from GET means this key is absent. A transport failure is a different result; unlimited fallback work during an outage can overwhelm the origin."],"cost":"Shared pools save connection setup; their total size, retries and waiting must fit the deployment’s capacity budget.","family":"Around Go: data stores","flow":["Shared client","Bounded operation","Value / miss / failure","Deliberate fallback"],"ratings":[],"strengths":["Configure go-redis deadlines, connection budgets and explicit cache-miss behavior."]},"hint":"Choose behavior for each error class.","id":"datastores.redis-client","introduction":"Redis is often used as a low-latency data-structure service, but the network, client pool and command cost still exist. Create a shared client, keep a bounded operation context and distinguish redis.Nil from transport failures. A missing optional cache entry and an unavailable required store have different application contracts.","nuance":"redis.Nil from GET means this key is absent. A transport failure is a different result; unlimited fallback work during an outage can overwhelm the origin.","objective":"Configure go-redis deadlines, connection budgets and explicit cache-miss behavior.","question":"How should a GET cache miss differ from a transport error?","references":["https://redis.io/docs/latest/develop/clients/go/","https://redis.io/docs/latest/develop/clients/go/produsage/","https://pkg.go.dev/github.com/redis/go-redis/v9"],"reviewAnswer":"Means the key is absent, not a connection outage","reviewPrompt":"redis.Nil from GET","sections":[{"body":"This lesson uses github.com/redis/go-redis/v9 with v9.16.0 as an example pin. PoolSize and MaxActiveConns are distinct knobs; do not assume a pool’s preferred retained size is a universal hard ceiling. Confirm options against the pinned version rather than copying future-version defaults.","code":"rdb := redis.NewClient(&redis.Options{\n    Addr: addr, PoolSize: 16, MaxActiveConns: 16,\n    PoolTimeout: 200*time.Millisecond,\n    DialTimeout: time.Second, ReadTimeout: time.Second, WriteTimeout: time.Second,\n    ContextTimeoutEnabled: true, MaxRetries: -1,\n})\n// One application owner closes rdb after in-flight work drains.","language":"go","title":"Construct one client with explicit example budgets","walkthrough":"The values illustrate a bounded small-client configuration, with automatic retries disabled so policy is visible. Production TLS, authentication and addresses come from configuration; re-enable suitable retries only with an overall operation budget and duplicate-effect analysis."},{"body":"redis.Nil represents a missing key for a GET, not a dead server. Preserve other errors so a caller can apply the intended fallback or failure policy. A fallback that recomputes expensive data on every transport failure can overwhelm the primary database during a Redis outage.","code":"value, err := rdb.Get(ctx, key).Result()\nswitch {\ncase errors.Is(err, redis.Nil):\n    return loadFromOrigin(ctx, key)\ncase err != nil:\n    return \"\", fmt.Errorf(\"cache read: %w\", err)\ndefault:\n    return value, nil\n}","language":"go","title":"Handle absence explicitly","walkthrough":"This is a helper returning string and error. The application supplies a bounded ctx and loadFromOrigin; the example deliberately surfaces infrastructure failure instead of silently starting unlimited origin requests."},{"body":"Later client versions can change pooling and pipeline behavior. Pin and test the version used by the service, including cancellation and saturation. These native network examples are not executable Redis access inside the app’s WASI sandbox; they teach the surrounding Go service environment.","title":"Keep version and workload assumptions visible"}],"takeaway":"Reuse the client, configure bounded waiting and handle value, miss and outage separately. Fallback and retry behavior are application decisions, not invisible conveniences.","title":"Redis: share the client and distinguish a miss from an outage","unitID":"datastores","wrongAnswers":["Treat both as evidence that Redis lost every key","Assume both guarantee an origin database request will be cheap"]},{"conceptTag":"datastores.redis-cache","designGuide":{"cautions":["In-process coalescing does not coordinate other replicas or make invalidation races disappear."],"cost":"Caching adds duplicate state, invalidation and miss coordination; measure saved origin work against stale-data risk.","family":"Around Go: data stores","flow":["Lookup","Bounded origin fill","Publish with TTL","Invalidate or expire"],"ratings":[],"strengths":["Design expiry, invalidation, negative caching and stampede control deliberately."]},"hint":"Consider the empty-cache path, including all replicas.","id":"datastores.redis-cache","introduction":"A cache duplicates another source of truth, so freshness and ownership must be explicit. Cache-aside reads can miss together, all query the origin and then repopulate the same key. TTL bounds one kind of staleness; it does not prevent a stampede or make a read-modify-write sequence correct.","nuance":"In-process coalescing does not coordinate other replicas or make invalidation races disappear.","objective":"Design expiry, invalidation, negative caching and stampede control deliberately.","question":"Why is cache-aside alone insufficient protection during a burst of misses?","references":["https://redis.io/docs/latest/commands/set/","https://pkg.go.dev/golang.org/x/sync/singleflight","https://redis.io/docs/latest/commands/ttl/"],"reviewAnswer":"Does not prevent misses from flooding the origin","reviewPrompt":"Cache TTL","sections":[{"body":"Use one SET operation with expiry when creating an expiring value. A separate SET followed by EXPIRE leaves a failure window where the key can survive without the intended lifetime. An ordinary later SET can also change existing TTL behavior, so decide the overwrite policy.","code":"redis-cli SET demo:product:42 '{\"name\":\"tea\"}' EX 60\nredis-cli GET demo:product:42\nredis-cli TTL demo:product:42","language":"bash","title":"Set value and expiration together","walkthrough":"Run against an isolated development Redis using the demo namespace. TTL reports remaining expiry state, not freshness relative to a database update that happened after the value was cached."},{"body":"Coalesce identical in-process fills and independently bound the total number of origin calls. A per-key singleflight group only coordinates callers in this process; many service replicas can still miss together. Optional TTL jitter spreads expirations but does not guarantee a global rate limit.","code":"_, err := rdb.Set(ctx, key, encoded, 60*time.Second).Result()\nif err != nil { return fmt.Errorf(\"cache fill: %w\", err) }\n// A bounded loader owns misses; do not start one goroutine per waiting caller.","language":"go","title":"Bound concurrent misses","walkthrough":"The fragment shows the atomic value-plus-expiry client operation after an origin load. It does not implement coalescing or cross-process coordination; those policies belong to the loader boundary and must be tested separately."},{"body":"Negative caching can reduce repeated absent-item lookups, but use a short deliberate lifetime and a representation distinct from a real value. A database update followed by cache deletion can race with an older in-flight fill. Use versioned keys or another coherent invalidation design when that stale-write window is unacceptable.","title":"Handle stale and missing data as distinct cases"}],"takeaway":"Set TTL atomically, bound origin fills and define the acceptable stale window. TTL, coalescing and invalidation address different failure modes.","title":"Redis cache-aside: TTLs do not solve concurrent fills","unitID":"datastores","wrongAnswers":["Only a longer TTL on keys that have not been created yet","One unlimited goroutine for every origin request"]},{"conceptTag":"datastores.redis-pipeline","designGuide":{"cautions":["MULTI/EXEC does not roll back already executed commands after a runtime command error."],"cost":"Batches reduce network round trips while retaining command/reply memory and increasing ambiguous partial-outcome work.","family":"Around Go: data stores","flow":["Bounded batch","One network exchange","Per-command result","Partial-failure policy"],"ratings":[],"strengths":["Bound command batches, inspect command errors and separate batching from atomicity."]},"hint":"Transport batching and a transactional boundary are different.","id":"datastores.redis-pipeline","introduction":"Pipelining lets a client send multiple commands without waiting for every individual round trip. It can improve throughput for independent work, but it does not make the group indivisible. Large batches also retain commands and replies in memory and can worsen latency for other work.","nuance":"MULTI/EXEC does not roll back already executed commands after a runtime command error.","objective":"Bound command batches, inspect command errors and separate batching from atomicity.","question":"What does pipelining guarantee about the whole batch?","references":["https://redis.io/docs/latest/develop/using-commands/pipelining/","https://redis.io/docs/latest/develop/using-commands/transactions/","https://pkg.go.dev/github.com/redis/go-redis/v9#Pipeliner"],"reviewAnswer":"Batches round trips without making the group atomic","reviewPrompt":"Redis pipeline","sections":[{"body":"Queue a small known batch and inspect the returned command objects. An error from Exec needs interpretation alongside each command result. A connection failure can leave the caller uncertain which writes the server executed; a batch is not an automatic rollback boundary.","code":"pipe := rdb.Pipeline()\na := pipe.Get(ctx, \"demo:a\")\nb := pipe.Get(ctx, \"demo:b\")\n_, err := pipe.Exec(ctx)\nif err != nil && !errors.Is(err, redis.Nil) { return err }\nfor _, cmd := range []*redis.StringCmd{a, b} {\n    if cmd.Err() != nil && !errors.Is(cmd.Err(), redis.Nil) { return cmd.Err() }\n}","language":"go","title":"Batch independent work","walkthrough":"This fragment batches two independent reads and tolerates missing keys explicitly. A write pipeline needs its own partial-outcome and retry policy; replaying all writes after an ambiguous error can duplicate effects."},{"body":"MULTI/EXEC groups commands atomically with respect to interleaving, but runtime command errors do not provide relational-database rollback. WATCH adds optimistic checks and can require a whole retry. A Lua script can perform a short conditional transition, but expensive scripts block other work on the server execution path.","code":"redis-cli <<'REDIS'\nMULTI\nSET demo:a 1\nINCR demo:count\nEXEC\nREDIS","language":"bash","title":"Choose atomicity separately","walkthrough":"The heredoc sends all commands through one redis-cli connection against an isolated development instance. Starting separate redis-cli processes for MULTI and EXEC would not create one transaction; connection ownership is part of the protocol."},{"body":"Cap commands and total encoded bytes, not only the number of business items. Measure batch duration, reply sizes and tail latency while other clients work. Client versions may use separate pipeline pools, so inspect the pinned version when calculating deployment-wide connection limits.","title":"Set a memory and latency budget for batches"}],"takeaway":"Batch bounded independent work to reduce round trips, and choose atomicity and retry semantics explicitly. Inspect partial outcomes rather than assuming Exec implies rollback.","title":"Redis pipelines save round trips; they are not transactions","unitID":"datastores","wrongAnswers":["Every earlier write rolls back if a later command errors","No other client can execute a command between its commands"]},{"conceptTag":"datastores.redis-coordination","designGuide":{"cautions":["Expiry changes the Redis key, not the execution state of an old process. A paused former owner can resume after a new owner starts; the protected resource may need fencing."],"cost":"Atomic scripts add protocol and recovery complexity; a lease is weaker than a durable resource-side ownership guarantee.","family":"Around Go: data stores","flow":["Atomic transition","Ownership token","Expiry or result","Downstream invariant"],"ratings":[],"strengths":["Avoid split increment/expiry races and unsafe lock deletion."]},"hint":"A key’s lifetime and a process’s execution lifetime differ.","id":"datastores.redis-coordination","introduction":"A counter with a timeout and a temporary ownership key look small, but concurrent requests and pauses expose their failure windows. Put dependent steps in one short atomic transition and distinguish an expired lease from a durable guarantee that only one worker can ever act.","nuance":"Expiry changes the Redis key, not the execution state of an old process. A paused former owner can resume after a new owner starts; the protected resource may need fencing.","objective":"Avoid split increment/expiry races and unsafe lock deletion.","question":"Why can a resource still need fencing after a lease expires?","references":["https://redis.io/docs/latest/commands/incr/","https://redis.io/docs/latest/develop/programmability/eval-intro/","https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/"],"reviewAnswer":"Does not stop a paused former owner from continuing","reviewPrompt":"Expired lease","sections":[{"body":"INCR followed by EXPIRE in separate operations can leave a counter without expiry if the client fails between them. A short script can attach expiry only when the counter is first created. This is an anchored fixed-window example, not a smooth sliding-window limiter.","code":"counter := redis.NewScript(`\nlocal n = redis.call(\"INCR\", KEYS[1])\nif n == 1 then redis.call(\"PEXPIRE\", KEYS[1], ARGV[1]) end\nreturn n\n`)\nn, err := counter.Run(ctx, rdb, []string{\"demo:rate\"}, 1000).Int64()\nif err != nil { return err }\nif n > 100 { return ErrLimited }","language":"go","title":"Make a fixed-window counter transition atomic","walkthrough":"The go-redis script API passes one explicitly named development key and a positive window in milliseconds. This example permits 100 events in a window anchored at the first increment; ErrLimited is an application error. Define unavailable-store behavior separately."},{"body":"SET key token NX PX can create a temporary lease. Release by checking the stored token and deleting in the same atomic operation, not by a GET and later DEL. Generate a unique token for each acquisition; a stale owner must not remove a new owner’s lease.","code":"release := redis.NewScript(`\nlocal current = redis.call(\"GET\", KEYS[1])\nif current == ARGV[1] then\n  return redis.call(\"DEL\", KEYS[1])\nend\nreturn 0\n`)\n// token is unique to this successful SET key token NX PX acquisition.\ndeleted, err := release.Run(ctx, rdb, []string{key}, token).Int64()\nif err != nil { return err }\n_ = deleted // 0 means the lease no longer belongs to this acquisition.","language":"go","title":"A lease must be released only by its owner","walkthrough":"The script compares the acquisition token inside the server before deletion. It solves that release race, but a paused worker may still continue after its lease expires; a protected resource may need fencing or another stronger ownership mechanism."},{"body":"An acknowledgment can be lost, a lease can expire during a pause and failover can change which writes survive. A Redis key alone is not a proof of exclusive business execution across failures. Use resource-side idempotency, version checks or fencing when duplicate work could violate an invariant.","title":"Explain the failure model before calling it a lock"}],"takeaway":"Make dependent counter steps atomic and release leases by token. Design the downstream invariant for pauses, ambiguity and expired ownership.","title":"Redis counters and leases need atomic transitions and ownership","unitID":"datastores","wrongAnswers":["Redis pauses every process that previously held the key","A unique token prevents all network failures"]},{"conceptTag":"datastores.redis-streams","designGuide":{"cautions":["The effect may commit before a worker crashes without acknowledging. Redelivery can then repeat it; pending-entry recovery needs destination-side idempotency."],"cost":"Consumer groups need retention, pending-work recovery, idempotent effects and explicit storage durability.","family":"Around Go: data stores","flow":["Read group entry","Apply idempotent effect","Acknowledge","Recover pending work"],"ratings":[],"strengths":["Understand consumer groups, pending entries, redelivery and bounded retention."]},"hint":"The worker can fail between the effect and acknowledgment.","id":"datastores.redis-streams","introduction":"A consumer group tracks delivery and acknowledgment, not automatic exactly-once application effects. A worker may crash after updating another database but before XACK. Redelivery is useful recovery, so the handler must recognize an operation it has already applied.","nuance":"The effect may commit before a worker crashes without acknowledging. Redelivery can then repeat it; pending-entry recovery needs destination-side idempotency.","objective":"Understand consumer groups, pending entries, redelivery and bounded retention.","question":"A consumer performed its external effect but crashed before acknowledging. What can later recovery cause?","references":["https://redis.io/docs/latest/commands/xreadgroup/","https://redis.io/docs/latest/commands/xautoclaim/","https://redis.io/docs/latest/commands/xack/"],"reviewAnswer":"Can cause redelivery after an effect already happened","reviewPrompt":"Crash before XACK","sections":[{"body":"In an isolated development instance, create a stream and group and append a demonstration event. XREADGROUP with > asks for new entries for this group. Acknowledge only after the application’s durable effect succeeds.","code":"redis-cli XGROUP CREATE demo:events workers 0 MKSTREAM\nredis-cli XADD demo:events '*' operationID order-42 kind created\nredis-cli XREADGROUP GROUP workers worker-1 COUNT 10 STREAMS demo:events '>'","language":"bash","title":"Read new entries with one group","walkthrough":"Replace worker names per process and retain the stream entry ID returned by the read. The demonstration group starts from 0 intentionally; starting at $ instead changes whether existing history is delivered."},{"body":"A delivered but unacknowledged entry remains pending for the group. Inspect pending work and use a supported reclaim mechanism after an appropriate idle threshold. A slow healthy worker and a dead worker can look alike, so claiming work must not assume the old consumer has physically stopped.","code":"redis-cli XPENDING demo:events workers\nredis-cli XAUTOCLAIM demo:events workers worker-2 60000 0-0 COUNT 10\n# After the effect succeeds, acknowledge its actual returned entry ID:\n# redis-cli XACK demo:events workers 1710000000000-0","language":"bash","title":"Inspect and reclaim pending entries","walkthrough":"XAUTOCLAIM requires a compatible server version and returns a continuation cursor as well as claimed entries. Iterate with explicit work bounds; the sample acknowledgment ID is a placeholder, not a success shortcut."},{"body":"Deduplicate the operation at the durable destination and treat replay as a normal path. Configure stream trimming so it does not discard work that still matters to consumers. Acknowledgment does not itself specify Redis persistence, replication acknowledgment or recovery guarantees; test those separately for the deployment.","title":"Keep delivery, retention and durability distinct"}],"takeaway":"Acknowledge after a durable idempotent effect, recover pending work deliberately, and budget retention and storage independently of consumer-group delivery.","title":"Redis Streams: acknowledge after the durable effect","unitID":"datastores","wrongAnswers":["Consumer groups roll back all external databases on failure","Reading with > guarantees an entry is delivered only once forever"]},{"conceptTag":"datastores.redis-load","designGuide":{"cautions":["SLOWLOG measures server execution. Callers can still wait for a client connection or network response; retries can then amplify load or repeat an ambiguous write."],"cost":"Latency and eviction policies trade memory, availability and persistence work; client concurrency cannot remove a hot-key bottleneck.","family":"Around Go: data stores","flow":["Client wait","Command work","Memory and persistence","Bounded recovery"],"ratings":[],"strengths":["Inspect server latency and memory while bounding client work and retry amplification."]},"hint":"Locate waiting before and after server command execution.","id":"datastores.redis-load","introduction":"Redis command latency can rise because of expensive commands, a hot key, big values, persistence work, network delay or waiting in the client. A low average hides queues and timeout bursts. Correlate request errors with server and client evidence before increasing goroutines or connection limits.","nuance":"SLOWLOG measures server execution. Callers can still wait for a client connection or network response; retries can then amplify load or repeat an ambiguous write.","objective":"Inspect server latency and memory while bounding client work and retry amplification.","question":"Why can callers time out while SLOWLOG shows no slow commands?","references":["https://redis.io/docs/latest/operate/oss_and_stack/management/optimization/latency/","https://redis.io/docs/latest/commands/scan/","https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/","https://redis.io/docs/latest/operate/oss_and_stack/management/replication/"],"reviewAnswer":"Does not exclude client-pool or network latency","reviewPrompt":"Quiet SLOWLOG","sections":[{"body":"In an authorized development environment, inspect memory, command statistics and recent slow commands. SLOWLOG measures server command execution, not every network or client-pool delay. Keep raw keys and command arguments out of broadly shared diagnostics when they may contain user data.","code":"redis-cli INFO memory\nredis-cli INFO stats\nredis-cli INFO commandstats\nredis-cli SLOWLOG GET 10\nredis-cli LATENCY LATEST","language":"bash","title":"Use focused observation commands","walkthrough":"Metrics and latency monitoring availability depend on server configuration and permissions. Compare the same time window with client pool wait and request p99; a quiet SLOWLOG does not prove that callers were fast."},{"body":"KEYS can block while traversing a large keyspace. SCAN divides that work into cursor-driven steps, but it is not a snapshot, COUNT is a hint and keys may appear more than once. Keep downstream handling idempotent and avoid moving all returned keys into one giant slice.","code":"redis-cli SCAN 0 MATCH 'demo:*' COUNT 100\n# Continue with the returned cursor until it is 0.\nredis-cli MEMORY USAGE demo:product:42","language":"bash","title":"Scan incrementally and cap batch work","walkthrough":"A single SCAN call is not a complete inventory. Even incremental maintenance needs rate and time budgets; do not run an unbounded sweep simply because each individual command looks small."},{"body":"Eviction policy and persistence determine whether a value can disappear and what survives failure. Replication is not automatically synchronous durability. Retrying INCR after a lost response may apply the effect twice; use an operation identifier and a suitable atomic protocol when duplicate effects are unacceptable. Bound retries within one deadline and measure recovery after overload.","title":"Define storage and retry guarantees"}],"takeaway":"Separate client wait from server execution, keep maintenance incremental and design for eviction, persistence and ambiguous write outcomes. More concurrency is not a repair for a hot bottleneck.","title":"Redis under load: hot keys, memory pressure and ambiguous retries","unitID":"datastores","wrongAnswers":["Redis always measures the full HTTP request path","SCAN COUNT imposes an exact global rate limit"]},{"conceptTag":"stdlib.borrowed-buffers","designGuide":{"cautions":["Clip does not copy","Sending a slice does not freeze it","Reset is not secret erasure"],"cost":"One deliberate copy buys independent result lifetime. Measure the boundary rather than guessing from allocation count.","family":"Byte ownership","flow":["Buffer owns storage","Bytes borrows a view","Clone retained result","Owner may reset"],"ratings":[],"strengths":["Borrow for immediate synchronous work","Copy only at a lifetime boundary","Document validity in the API"]},"hint":"A second descriptor still refers to the same backing array.","id":"stdlib.borrowed-buffers","introduction":"A byte slice can be a borrowed window rather than an owned result. bytes.Buffer.Bytes exposes unread storage, and Scanner.Bytes exposes a token with a limited lifetime. The type []byte does not express that lifetime. Draw the owner, the view and the next mutation before deciding whether to copy.","nuance":"Clone copies the bytes. Reset does not revoke aliases or promise to overwrite old storage. A channel send also copies a descriptor, so asynchronous consumption needs an ownership protocol.","objective":"Trace bytes.Buffer and Scanner views, then make retained results independent at a lifetime boundary.","question":"A result must survive bytes.Buffer.Reset and later writes. What establishes independent ownership?","references":["https://pkg.go.dev/bytes#Buffer.Bytes","https://pkg.go.dev/bytes#Clone","https://pkg.go.dev/bufio#Scanner.Bytes","https://go.dev/ref/spec#Slice_types"],"reviewAnswer":"Copy before owner changes","reviewPrompt":"Keep borrowed bytes after reuse?","sections":[{"body":"Draw a row of bytes for the buffer, then a window labeled view above it. Bytes does not create a separate row. While the borrow is valid, changing an element through the view changes the buffer. A separate copy belongs on a second row with no shared storage.","code":"package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n)\n\nfunc main() {\n    var buffer bytes.Buffer\n    buffer.WriteString(\"alpha\")\n    view := buffer.Bytes()\n    owned := bytes.Clone(view)\n    view[0] = 'A'\n    fmt.Println(buffer.String())\n    buffer.Reset()\n    buffer.WriteString(\"omega\")\n    fmt.Println(string(owned))\n}","language":"go","title":"One owner, one temporary view","walkthrough":"The output is Alpha, then alpha. The first print demonstrates aliasing before reset. bytes.Clone creates the owned result before the owner changes. The program deliberately never inspects view after reset: its old contents are not a valid result to rely on."},{"body":"Follow this order: obtain a view, consume it synchronously, then mutate or release the owner. If you must return, cache or enqueue the result beyond that boundary, copy the bytes or transfer the owner explicitly. Assigning the slice to another variable copies its descriptor and preserves sharing. Clip also keeps the existing elements shared.","title":"The lifetime timeline"},{"body":"Scanner.Bytes may expose storage reused by the next Scan. A token consumed immediately can remain borrowed. A token saved in a collection needs its own bytes. Check Scanner.Err after the loop as a separate requirement; correct ownership does not make input parsing infallible.","code":"package main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    scanner := bufio.NewScanner(strings.NewReader(\"red\\nblue\\n\"))\n    var saved [][]byte\n    for scanner.Scan() {\n        saved = append(saved, bytes.Clone(scanner.Bytes()))\n    }\n    if err := scanner.Err(); err != nil {\n        panic(err)\n    }\n    for _, token := range saved {\n        fmt.Println(string(token))\n    }\n}","language":"go","title":"Scanner tokens need the same decision","walkthrough":"Each iteration copies the current token before the next Scan can replace it. The saved values therefore print red and blue. Without a copy, storing the slice descriptors would not establish a durable token contract. The final error check handles scanning failures independently."},{"body":"A successful channel send transfers the slice descriptor, not an immutable snapshot. The producer must stop using the storage until consumption finishes, or send an owned copy. For cancellation, specify who owns a buffer when enqueueing fails and who releases it after a successful handoff.","title":"Asynchronous work crosses the boundary"},{"body":"Reset prepares a buffer for reuse and can retain its allocation. It does not guarantee erasure of sensitive bytes. Test that an owned result remains unchanged after later buffer operations. Avoid tests that require a particular stale value from an invalid view, and measure retained memory when large buffers live much longer than their input.","title":"Reset, retention and tests"}],"takeaway":"A borrowed result is safe only within its documented lifetime. Draw the next mutation or release, then copy before that boundary when the caller needs a durable value. Test independence of valid results rather than the contents of invalid views.","title":"Borrow bytes briefly; copy before their owner changes","unitID":"stdlib","wrongAnswers":["Clip the view to its length","Assign the slice to a new name"]},{"conceptTag":"runtime.pool-ownership","designGuide":{"cautions":["No access after Put","No guaranteed object retention","No hard memory bound"],"cost":"Extra ownership protocol and possible retained capacity. Keep an unpooled baseline and discard oversized objects according to workload.","family":"Temporary object reuse","flow":["Get temporary object","One exclusive owner","Copy external result","Put ends ownership"],"ratings":[],"strengths":["Reuse measured temporary allocation","Keep the boundary in one small function","Correct with reuse or fresh allocation"]},"hint":"A later owner may reuse storage immediately; the returned value needs a separate lifetime.","id":"runtime.pool-ownership","introduction":"Pooling can reduce temporary allocation, but every Get and Put creates an ownership obligation. A former owner must stop using the object after Put. A result that still aliases the object violates that obligation even when the code compiles and a small benchmark looks fast.","nuance":"Pool reuse is optional and identity is not guaranteed. An owned copy remains correct with or without reuse. A pool does not replace admission control, a bounded queue or database connection management.","objective":"Use sync.Pool with exclusive ownership, independent output and an explicit policy for oversized buffers.","question":"A function returns a buffer to sync.Pool. How can its returned []byte remain safe for the caller?","references":["https://pkg.go.dev/sync#Pool","https://pkg.go.dev/bytes#Buffer","https://go.dev/doc/gc-guide","https://go.dev/doc/articles/race_detector","https://pkg.go.dev/testing"],"reviewAnswer":"Copy before Put","reviewPrompt":"Return pooled buffer bytes?","sections":[{"body":"Follow Get to one active owner, then produce an independent result before Put. After release, the old owner must not read or write the buffer. The pool can discard objects and Get need not return a previously stored object, so correctness must work with both reuse and a fresh allocation.","title":"Draw the ownership cycle"},{"body":"This encoder returns owned bytes. Its example cutoff avoids deliberately returning an oversized backing buffer to this pool. The cutoff is a workload policy, not a universal value and not a cap on total process memory.","code":"package main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"sync\"\n)\n\nvar buffers = sync.Pool{New: func() any {\n    return new(bytes.Buffer)\n}}\n\nfunc encode(name string) []byte {\n    buffer := buffers.Get().(*bytes.Buffer)\n    buffer.Reset()\n    buffer.WriteString(\"hello, \")\n    buffer.WriteString(name)\n    result := bytes.Clone(buffer.Bytes())\n    if buffer.Cap() <= 64*1024 {\n        buffer.Reset()\n        buffers.Put(buffer)\n    }\n    return result\n}\n\nfunc main() {\n    first := encode(\"Ada\")\n    _ = encode(\"Grace\")\n    fmt.Println(string(first))\n}","language":"go","title":"Copy the result before releasing its storage","walkthrough":"The output remains hello, Ada after another encode. bytes.Clone separates the result from temporary storage before Put. The example never assumes the second call gets the same buffer. Buffers larger than the illustrative cutoff are discarded from this reuse path, while active requests and returned results still consume memory."},{"body":"sync.Pool is not a bounded cache, a reliable queue, or a database connection manager. Objects can disappear without explicit removal. A strict concurrency limit needs admission control; a database connection needs its client library's capacity, timeout and cleanup rules. A pool alone establishes none of those contracts.","title":"Do not turn a pool into a resource budget"},{"body":"Keep the first result, make many later calls, and verify the first bytes remain unchanged. Add parallel calls under the race detector. Do not assert that a specific object returns from Get. Test large and small inputs, and check cancellation ownership if work is queued to another goroutine.","title":"Test public independence, not object identity"},{"body":"Compare a correct unpooled baseline against the pooled version using realistic response-size distributions. Measure allocations, retained memory and latency after bursts. Race instrumentation is for correctness checks, not production timing claims. If pooling adds complexity without a measurable benefit, keep the simpler owned-result implementation.","title":"Make the optimization earn its protocol"}],"takeaway":"Get gives temporary exclusive access; Put ends it. Make external results independent before release, avoid identity assumptions and measure whether pooling helps. A per-object size cutoff does not bound total memory or concurrent work.","title":"A pool reuses temporary objects; it does not own your results","unitID":"runtime","wrongAnswers":["Read it after Put if usually unchanged","Require Get to return the last object"]},{"afterLessonID":"stdlib.json","conceptTag":"stdlib.json-v2-contracts","designGuide":{"cautions":["Go compatibility does not imply that selecting different serializer defaults preserves your application protocol."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"JSON v2: migrate behavior, not just imports","flow":["Record the contract","Compare v1 and v2","Opt into one change","Verify old consumers"],"ratings":[],"strengths":["Compare null, empty and omitted JSON values before changing a public API.","Preserve the established JSON contract first. Enable an intentional representation change only when fixtures and consumers agree about its meaning."]},"hint":"A new API surface and a new wire representation are separate changes.","id":"stdlib.json-v2-contracts","introduction":"Go 1.27 includes encoding/json/v2 without an experiment flag. Keeping encoding/json preserves its v1 behavior; adopting the v2 API is a separate decision. A compiling change can still alter a mobile model, persisted event or generated client. Write the expected wire representation before migrating.","nuance":"Go compatibility does not imply that selecting different serializer defaults preserves your application protocol.","objective":"Compare null, empty and omitted JSON values before changing a public API.","question":"An existing endpoint must keep nil maps encoded as null during migration. Which approach fits?","references":["https://go.dev/doc/jsonv2-migration","https://pkg.go.dev/encoding/json/v2","https://gopherforge.app/news/go-json-v2-migration-api-compatibility"],"reviewAnswer":"Preserve, compare, then opt in","reviewPrompt":"JSON v2 migration baseline?","sections":[{"body":"Ordinary nil slices and maps become empty collections under v2 defaults. V1 produces null. Neither representation is universally better: an established client may distinguish absence from an empty result. Keep fixtures for the actual exported types, including binary data and custom methods.","code":"package main\n\nimport (\n\tv1 \"encoding/json\"\n\tv2 \"encoding/json/v2\"\n\t\"fmt\"\n)\n\ntype Page struct {\n\tItems  []string          `json:\"items\"`\n\tLabels map[string]string `json:\"labels\"`\n}\n\nfunc main() {\n\told, err := v1.Marshal(Page{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tnext, err := v2.Marshal(Page{})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(string(old))\n\tfmt.Println(string(next))\n}\n\n// Output:\n// {\"items\":null,\"labels\":null}\n// {\"items\":[],\"labels\":{}}\n","language":"go","title":"Compare a zero-valued response","walkthrough":"The two valid JSON documents carry different collection shapes. This complete program uses only the Go 1.27 standard library. The panic checks belong to a small demonstration; an application boundary should return and classify encoding errors."},{"body":"DefaultOptionsV1 supplies the compatibility baseline through the v2 API. Later options override earlier ones, so opt into one reviewed change and keep the rest of the contract stable. A compatibility option does not validate domain data or automatically version persisted messages.","code":"data, err := jsonv2.Marshal(response,\n\tjsonv1.DefaultOptionsV1(),\n\tjsonv2.FormatNilSliceAsNull(false),\n)\nif err != nil {\n\treturn nil, fmt.Errorf(\"encode response: %w\", err)\n}\nreturn data, nil","language":"go","title":"Preserve first, opt in deliberately","walkthrough":"This function-body fragment imports encoding/json as jsonv1, encoding/json/v2 as jsonv2, and fmt. response is the application value. Only nil-slice formatting is deliberately changed; nil-map behavior stays at the chosen v1 baseline."},{"body":"Compare typed meaning and exact bytes separately. Sorted map output is useful for snapshots, but deterministic encoding is not a universal canonicalization format for signatures. Include old stored records, custom marshalers and independently released consumers, then stage the rollout with sampled comparisons and a format-aware rollback.","title":"Test old readers as well as new writers"},{"body":"Keep an empty response fixture and a nonempty one. Change one option, predict the output, run both packages and explain which consumer needs the old result. The longer workshop on the website includes strict decoding, race-tested contract examples and a bounded fuzz target. It is useful preparation before a repository-wide import rewrite.","title":"Extend the exercise"}],"takeaway":"Preserve the established JSON contract first. Enable an intentional representation change only when fixtures and consumers agree about its meaning.","title":"JSON v2: migrate behavior, not just imports","unitID":"stdlib","wrongAnswers":["Replace every import and trust the compiler","Make every field a string"]},{"conceptTag":"stdlib.json-presence","designGuide":{"cautions":["A tag controls encoding behavior; it does not define authorization, business validation or every partial-update transition."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"JSON presence: omitted, zero and null are different states","flow":["List input states","Choose update semantics","Decode fresh data","Assert stored effects"],"ratings":[],"strengths":["Choose omitempty, omitzero and request presence models from the endpoint contract.","Specify presence semantics before choosing tags or pointer fields. Missing, null and a concrete zero value may represent different commands."]},"hint":"Ask what a pointer contains after null and after an omitted property.","id":"stdlib.json-presence","introduction":"A JSON object can omit a member, contain null, or contain a concrete zero value. Go fields alone do not always preserve those distinctions. An update that sets enabled to false must not silently become an instruction to leave enabled unchanged. Start with a state table for the operation.","nuance":"A tag controls encoding behavior; it does not define authorization, business validation or every partial-update transition.","objective":"Choose omitempty, omitzero and request presence models from the endpoint contract.","question":"Ordinary decoding into a fresh *bool must distinguish missing, null and false. What is missing from that representation?","references":["https://pkg.go.dev/encoding/json","https://pkg.go.dev/encoding/json/v2"],"reviewAnswer":"Absent and null can both become nil","reviewPrompt":"PATCH with *bool: all states?","sections":[{"body":"Under v1 defaults, omitempty omits a zero integer and false boolean. Under v2 defaults those are nonempty JSON values and remain present. omitzero expresses Go zero-value omission. Do not replace tags mechanically: some response fields must be visible even when false or zero.","code":"type Flags struct {\n\tCount   int  `json:\"count,omitempty\"`\n\tEnabled bool `json:\"enabled,omitempty\"`\n}\n\n// v1 zero value: {}\n// v2 zero value: {\"count\":0,\"enabled\":false}\ntype OptionalCount struct {\n\tCount int `json:\"count,omitzero\"`\n}","language":"go","title":"Compare omission rules","walkthrough":"These declarations compare ordinary scalar fields. They do not describe every custom marshaler. Build table tests for zero, nonzero, nil and explicitly empty values on the actual request or response type."},{"body":"A bool stores true or false, not whether a property was absent. A *bool can distinguish absent from false in a freshly decoded value, but ordinary decoding also maps explicit null to nil. If null means clear while absence means keep, use a documented presence-aware representation or an explicit operation type.","title":"Do not use an ordinary bool as a PATCH protocol"},{"body":"For a full replacement command, decide required fields and validate the final state. For a partial update, separately validate which transitions are allowed. Avoid reusing an already populated decoding target: fields absent from input can retain earlier state and make missing values appear supplied.","title":"A complete update has a simpler contract"},{"body":"Test an omitted property, null, false and true independently. Assert both the final stored value and whether a write occurs. Add unknown members and malformed values to the matrix, and verify that decoding or validation failure cannot publish a partial update.","title":"Write the four cases before the code"}],"takeaway":"Specify presence semantics before choosing tags or pointer fields. Missing, null and a concrete zero value may represent different commands.","title":"JSON presence: omitted, zero and null are different states","unitID":"stdlib","wrongAnswers":["Pointers always distinguish all three states","omitempty validates required input"]},{"conceptTag":"stdlib.json-input-policy","designGuide":{"cautions":["Strict decoding cannot authorize a resource or make an external write exactly once."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"Strict JSON input: reject ambiguity before side effects","flow":["Bound input bytes","Decode a fresh value","Validate and authorize","Publish only success"],"ratings":[],"strengths":["Separate JSON syntax acceptance, unknown-member policy and domain validation.","Bound input, decode under an explicit policy, validate the domain and authorize the target before performing a side effect. Test each boundary independently."]},"hint":"Duplicate names and unknown names are different cases.","id":"stdlib.json-input-policy","introduction":"Successful decoding proves only that input was accepted under the decoder policy. It does not authorize the caller or establish a valid business transition. V2 rejects duplicate names and invalid UTF-8 by default; exact field-name matching and unknown-member rejection are separate settings.","nuance":"Strict decoding cannot authorize a resource or make an external write exactly once.","objective":"Separate JSON syntax acceptance, unknown-member policy and domain validation.","question":"When should a decoder be expected to reject unknown JSON member names?","references":["https://pkg.go.dev/encoding/json/v2","https://pkg.go.dev/net/http#MaxBytesReader","https://go.dev/doc/security/fuzz/"],"reviewAnswer":"Only with the chosen strict policy","reviewPrompt":"Are unknown JSON names rejected?","sections":[{"body":"Unknown members are ignored by default in v2; use RejectUnknownMembers when the endpoint contract requires strict commands. A forward-compatible event consumer may need another policy. Bound body bytes before decoding and limit expensive domain work separately.","code":"func decodeName(data []byte) (string, error) {\n\tvar request struct {\n\t\tName string `json:\"name\"`\n\t}\n\tif err := jsonv2.Unmarshal(data, &request, jsonv2.RejectUnknownMembers(true)); err != nil {\n\t\treturn \"\", fmt.Errorf(\"decode name: %w\", err)\n\t}\n\tname := strings.TrimSpace(request.Name)\n\tif name == \"\" {\n\t\treturn \"\", errors.New(\"name required\")\n\t}\n\treturn name, nil\n}","language":"go","title":"Make the boundary policy visible","walkthrough":"The complete helper needs encoding/json/v2 aliased as jsonv2, fmt, strings and errors. Its caller must cap data size before allocation. A fresh local target prevents earlier values or a partial failed decode from becoming a successful published result."},{"body":"Use fixtures for duplicate names, differently cased names, an unknown property, invalid UTF-8, a trailing second JSON value and a blank name. Record acceptance, typed value and domain-validation result. Do not decide compatibility solely from a changed error string.","title":"Test syntax and business meaning separately"},{"body":"A valid document or resource ID does not establish tenant access. Bind the caller scope to the authoritative lookup or update predicate. A timeout during a later external write can leave its result unknown, so strict JSON decoding is not a substitute for an idempotency protocol.","title":"Authorize after decoding, before acting"},{"body":"For arbitrary bounded bytes, assert that failed decoding returns no usable partial value. For accepted requests, check required invariants and a typed encode/decode round trip. Seed the ambiguity cases explicitly; a ten-second campaign explores inputs without proving every future input safe.","title":"Fuzz a meaningful contract"}],"takeaway":"Bound input, decode under an explicit policy, validate the domain and authorize the target before performing a side effect. Test each boundary independently.","title":"Strict JSON input: reject ambiguity before side effects","unitID":"stdlib","wrongAnswers":["Assume unknown names are always rejected","Compare decoder error messages only"]},{"conceptTag":"ai.go-workflow","designGuide":{"cautions":["A tool can generate and execute code while still misunderstanding the product invariant. Review behavior as well as syntax."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"A Go agent task starts with a contract and a failing example","flow":["State the defect","Inspect code and callers","Review a small patch","Run meaningful checks"],"ratings":[],"strengths":["Turn an ambiguous coding request into a small, verifiable Go change.","Define the contract, inspect the relevant code, make one reviewable change and require concrete evidence. Use the explanation to check understanding, not replace it."]},"hint":"Choose evidence another developer can reproduce.","id":"ai.go-workflow","introduction":"Claude Code, Codex and Cursor can inspect files, propose patches and run available tools. Useful work still needs a concrete behavior and a way to check it. In this unit you guide an agent in your own repository. Ordinary native projects stay local. The separate Playground adds explicit, opt-in sharing with people and MCP clients; it never uploads an existing project automatically.","nuance":"A tool can generate and execute code while still misunderstanding the product invariant. Review behavior as well as syntax.","objective":"Turn an ambiguous coding request into a small, verifiable Go change.","question":"An agent reports a fix but never names a reproducing input or test. What should you establish first?","references":["https://developers.openai.com/cookbook/examples/codex/iterating-development-workflows-with-codex","https://code.claude.com/docs/en/best-practices","https://cursor.com/docs/agent/overview","https://modelcontextprotocol.io/specification/2025-11-25/server/tools","https://learn.chatgpt.com/docs/extend/mcp","https://gopherforge.app/guide/mcp"],"reviewAnswer":"A contract and a failing example","reviewPrompt":"Start a Go agent task with?","sections":[{"body":"Suppose LowerBound returns an arbitrary duplicate index. Supply a minimal input, expected answer, supported Go version and public API constraint. Ask the agent to inspect the implementation and existing tests before proposing a change. A broad instruction such as improve search does not tell either of you which behavior matters.","code":"Task: fix LowerBound in internal/search.\nInput: [1, 3, 3, 8], target 3. Expected index: 1.\nPreserve the exported signature and half-open interval invariant.\nInspect existing callers and tests first. Add empty, missing and duplicate cases.\nRun: go test ./internal/search\nExplain why equality moves hi instead of returning immediately.","language":"text","title":"Give the task an observable result","walkthrough":"This is an example task prompt, not a tool-specific command. It names the defect, scope, invariant and verification. Replace paths with real repository paths; the agent must not invent a test result if the environment cannot run the command."},{"body":"Read the actual diff, including tests. A test that merely duplicates the new implementation may be green without protecting the contract. Ask which previous input fails, why the change fixes it and which other callers could observe a difference. Formatting changes should not hide the behavior change.","title":"Inspect before accepting a patch"},{"body":"An agent can miss an overflow, copy a mutex or drop a cancellation path while producing plausible prose. Identify the owner of mutable values, the lifetime of every goroutine and the meaning of public errors yourself. A small patch is easier to understand and revert than an unexplained rewrite.","title":"Keep human judgment at the boundary"},{"body":"Run the focused test, then the affected package checks. Record the actual compiler and command. If a remote integration service is unavailable, label that check unverified and keep an isolated reproduction. Passing unit tests is useful evidence; it is not proof about database failover or every interleaving.","title":"Repeat a reproducible check"},{"body":"For a collaborative Go task, read the current source and identify the state your edit is based on. GopherForge’s encrypted JavaScript MCP companion uses sourceHash; the compatible remote MCP uses an integer revision. Ask the agent to show its named cursor, describe the failing input and publish a small checked edit. Publishing source and requesting Test are not execution. A person presses Run or Test in their browser or native app; that execution client builds locally and shares a result labelled with its source and participant. The browser has its own Go/WASI worker. Native encrypted rooms require GopherForge 1.3.3 or newer; public 1.3.2 uses compatible rooms.","code":"Read sourceHash A (encrypted) or revision 7 (compatible)\n  ├─ checked edit → new source identity\n  ├─ request Test → awaiting local button\n  ├─ person presses Test on web/iPhone/iPad → local Go\n  └─ read the reported result for that captured source\n\nIf source has changed again, the earlier result is historical evidence.","language":"text","title":"A shared Playground keeps editing separate from execution","walkthrough":"The two protocols use different change guards; do not send an encryption key to the compatible remote endpoint. The JavaScript companion keeps its key client-side, but the selected MCP host and AI provider can read decrypted tool results. A reported pass applies to the captured source and environment, not automatically to the latest edit or every platform."},{"body":"A learner can explicitly publish a read-only progress link for a teacher or assistant. Ask for a short plan based on unfinished lessons and interview topics marked Revisit, then explain and solve a concrete exercise yourself. The snapshot is not an account or a competency certificate. A compiler mark describes a recorded lesson check; a self-reported reading mark describes study, not execution. Never let an assistant silently replace your learning record from another person’s URL.","title":"Use a published progress snapshot as teaching context"}],"takeaway":"Define the contract, inspect the relevant code, make one reviewable change and require concrete evidence. Use the explanation to check understanding, not replace it.","title":"A Go agent task starts with a contract and a failing example","unitID":"ai","wrongAnswers":["A larger rewrite with no constraints","A more confident completion message"]},{"conceptTag":"ai.repository-guidance","designGuide":{"cautions":["Do not share secret values in instruction files or assume that a context exclusion blocks all tool access."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"Repository guidance for Codex, Claude Code and Cursor","flow":["Document real commands","Choose tool-specific scope","Check loaded guidance","Enforce tool permissions"],"ratings":[],"strengths":["Write useful Go repository instructions without confusing context with permissions.","Keep repository facts concrete, scope guidance using each product’s documented mechanism and enforce permissions in the environment. Recheck discovery after tool changes."]},"hint":"Distinguish what the model is told from what its tools are allowed to do.","id":"ai.repository-guidance","introduction":"Durable guidance saves repeated explanation of layout, build commands and boundary rules. The supported discovery mechanisms differ between products and can change. Keep the repository facts stable, then consult the official documentation for how the installed tool discovers and scopes them.","nuance":"Do not share secret values in instruction files or assume that a context exclusion blocks all tool access.","objective":"Write useful Go repository instructions without confusing context with permissions.","question":"Repository guidance forbids production queries, but the agent still has a production credential. What should you conclude?","references":["https://learn.chatgpt.com/docs/agent-configuration/agents-md","https://code.claude.com/docs/en/memory","https://cursor.com/docs/rules","https://modelcontextprotocol.io/specification/2025-11-25/server/tools","https://learn.chatgpt.com/docs/extend/mcp"],"reviewAnswer":"Guidance is not an access control","reviewPrompt":"Do repo rules enforce access?","sections":[{"body":"Describe the real Go module, generated files, focused tests and opt-in integration environment. Use exact working directories and commands. Keep examples free of credentials and name environment variables without values. A new developer should be able to follow the same instructions without an agent.","code":"# Go service working agreements\n- Supported compiler: follow go.mod and the CI toolchain.\n- Unit checks: go test ./...\n- Worker changes: go test -race ./internal/worker/...\n- Generated API: run the pinned generator documented in docs/generate.md.\n- Integration checks use disposable databases; never production endpoints.\n- Preserve public error and JSON contracts unless the task changes them.","language":"markdown","title":"Write the repository facts once","walkthrough":"This illustrative guidance belongs in the repository instruction mechanism used by the selected tool. It is not an instruction for GopherForge itself. Replace package paths and generation commands with ones that exist in the actual checkout."},{"body":"Codex uses AGENTS.md with directory-scoped discovery and override rules. Claude Code uses CLAUDE.md and its documented rules and memory mechanisms. Cursor offers AGENTS.md and project rules in .cursor/rules with selectable scope. Do not assume copying one filename gives identical precedence in every product.","title":"Map facts to the tool deliberately"},{"body":"When guidance appears ignored, ask the tool which files it loaded and inspect its documented diagnostics. A nested instruction may override a general rule. Avoid growing one global instruction file into a second copy of the whole codebase; link concise maintained project documents where supported.","title":"Verify the loaded scope"},{"body":"A sentence saying do not access production is useful intent, but it does not revoke a credential. Use actual sandbox, approval and account controls in the environment. A rule file is not an authentication boundary, and ignoring a file for indexing does not necessarily prevent shell tools from reading it.","title":"Keep controls separate from prose"},{"body":"A repository instruction file and an MCP room capability solve different problems. Instructions describe how to work; a capability grants access to a selected room. Give an agent an Edit link only when it should change source, and a View link when it should review. Do not put bearer tokens in AGENTS.md, CLAUDE.md, a Cursor rule or a committed MCP configuration. An expiry or a closed room requires a new explicit connection, not a search through unrelated projects.","code":"Task contract:\n- Read the room and current revision.\n- Change only the named Go files.\n- Explain the invariant and minimal failing input.\n- Request a local test; wait for device Output.\n- Do not run on a server or claim an older result validates a new edit.","language":"text","title":"Give an MCP collaborator a bounded task","walkthrough":"The contract scopes both the edit and the evidence. The AI must first read the current room revision; the human then decides whether to execute that source on the local device. A repository rule never substitutes for the room capability or that local action."},{"body":"A mobile AI client can use a supported remote HTTPS MCP connector. The native app participates while foregrounded and executes only after its local button is pressed. Connector availability is controlled by the AI client and plan. Do not prescribe an npm daemon on iOS or claim that a custom remote URL automatically works in every mobile chat. Keep a readable web/JSON progress link as a simpler way to provide teaching context.","title":"Phone connection does not mean a background server on iOS"}],"takeaway":"Keep repository facts concrete, scope guidance using each product’s documented mechanism and enforce permissions in the environment. Recheck discovery after tool changes.","title":"Repository guidance for Codex, Claude Code and Cursor","unitID":"ai","wrongAnswers":["The heading style in the markdown file","Excluding one file from search alone"]},{"conceptTag":"ai.verify-generated-go","designGuide":{"cautions":["Compiling proves API compatibility for that build; database timing, failover and atomicity require additional evidence."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"Verify generated Go against the real module and runtime","flow":["Resolve the module","Inspect the real API","Trace ownership","Test the failure boundary"],"ratings":[],"strengths":["Catch invented APIs, unsafe concurrency and changed wire contracts in generated Go.","Resolve the actual version, compile the claimed API, review ownership and test changed public behavior. Keep native, WASI and remote-service evidence distinct."]},"hint":"Find the dependency already selected by the build.","id":"ai.verify-generated-go","introduction":"Generated source can look idiomatic while targeting the wrong driver major version or changing the public result. Compile against the selected module graph, inspect authoritative APIs and test the observable path. A plausible import name or confident explanation is not version evidence.","nuance":"Compiling proves API compatibility for that build; database timing, failover and atomicity require additional evidence.","objective":"Catch invented APIs, unsafe concurrency and changed wire contracts in generated Go.","question":"A MongoDB example uses an old driver signature but the module uses v2. Which is the useful first check?","references":["https://go.dev/ref/mod","https://go.dev/doc/articles/race_detector.html","https://www.mongodb.com/docs/drivers/go/current/","https://modelcontextprotocol.io/specification/2025-11-25/server/tools","https://learn.chatgpt.com/docs/extend/mcp"],"reviewAnswer":"Check the selected version and API","reviewPrompt":"Generated API mismatch. First?","sections":[{"body":"Start in the target module and inspect the workspace and selected dependencies. A local replace can make generated code compile against unreleased source. For MongoDB v2, use its /v2 path and documented lifecycle; do not add an old major version merely to make an invented call compile.","code":"go env GOMOD GOWORK\ngo list -m all\ngo doc go.mongodb.org/mongo-driver/v2/mongo.Connect\ngo test ./internal/store/...","language":"bash","title":"Check which module the code actually uses","walkthrough":"These are native-development commands in a repository that already depends on the v2 driver. go doc establishes the selected API rather than downloading a guessed dependency. The package test path must exist in that checkout."},{"body":"For every generated goroutine, identify who starts it, cancels it and waits for it. Check blocking sends and capacity acquisition. Acquiring a semaphore inside a newly launched goroutine can bound active work while still allowing an unbounded number of waiting goroutines.","title":"Review ownership before adding goroutines"},{"body":"A nil slice becoming empty changes JSON under some serializers. Replacing %w with %v changes error matching. Returning success after a canceled partial export changes the protocol. Add fixtures for those decisions and check old callers before accepting a cosmetic cleanup.","title":"Compare contracts, not just signatures"},{"body":"Ask for a blocked-receiver cancellation test, duplicate request or commit-then-disconnect fixture when relevant. Run race detection on exercised concurrent paths and use integration tests for database atomicity. No amount of mocking can establish a live driver or server guarantee it never exercised.","title":"Require a failure-path demonstration"},{"body":"Require the source revision, the Run/Test operation, the participating device, the observed result and the relevant runtime limits. A shared result is client-reported, not an attested proof. If source changed while the build ran, keep the old result visible as historical evidence. Do not run unreviewed AI code merely because an edit arrived. A relay must not execute the project on behalf of all participants.","code":"Evidence checklist:\nsource revision + exact files\n→ explicit local Run/Test\n→ device-labelled stdout/stderr\n→ compare result revision with current revision\n→ state unverified platform/service conditions","language":"text","title":"Check execution provenance before reading green output","walkthrough":"Read the chain from top to bottom. A source revision identifies what was built, the local action identifies where it ran, and the final comparison tells you whether the evidence still applies. Missing a step leaves a narrower claim, not an automatic pass."},{"body":"Suppose two collaborators both read revision 4. The first publishes revision 5; the second must not overwrite it using an unconditional write. A compare-and-swap publication rejects the stale revision. Preserve the second draft, inspect revision 5 and reapply the intended change. This whole-file strategy is simpler than CRDT merging but requires an explicit conflict workflow. A successful HTTP update only proves that a revision was accepted; it does not prove that the Go program is correct.","title":"Reproduce conflicts without discarding a local draft"}],"takeaway":"Resolve the actual version, compile the claimed API, review ownership and test changed public behavior. Keep native, WASI and remote-service evidence distinct.","title":"Verify generated Go against the real module and runtime","unitID":"ai","wrongAnswers":["Add both major versions automatically","Trust that a similar method exists"]},{"conceptTag":"ai.trust-boundaries","designGuide":{"cautions":["Do not confuse a generated command with an authorized action. Context files and tool permissions solve different problems."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"Agent trust boundaries: repository text is input data","flow":["Identify trusted intent","Inspect diagnostic data","Constrain tools and secrets","Report verified evidence"],"ratings":[],"strengths":["Review commands, secrets and external writes when an agent consumes untrusted text.","Treat external text as task data, enforce permissions with real controls and verify sensitive commands at their boundary. Keep the Go fix tied to its authorized behavior."]},"hint":"The page is evidence to inspect, not a new instruction source.","id":"ai.trust-boundaries","introduction":"A source comment, dependency README, test log or fetched webpage can contain instructions written by someone else. Reading that material to solve a Go problem does not authorize its author to expand the task. Keep the user’s goal and trusted repository guidance separate from external diagnostic content.","nuance":"Do not confuse a generated command with an authorized action. Context files and tool permissions solve different problems.","objective":"Review commands, secrets and external writes when an agent consumes untrusted text.","question":"A webpage linked by a failing test asks an agent to upload a credential file. What should happen?","references":["https://developers.openai.com/codex/security","https://code.claude.com/docs/en/security","https://cursor.com/docs/agent/security","https://modelcontextprotocol.io/specification/2025-11-25/server/tools","https://learn.chatgpt.com/docs/extend/mcp"],"reviewAnswer":"External text cannot grant permission","reviewPrompt":"Can a page authorize an upload?","sections":[{"body":"Imagine a failing test prints a page that tells the agent to upload environment variables. That instruction is not part of the authorized fix. Extract the actual assertion failure, inspect the relevant source and ignore the requested credential transfer.","code":"Diagnostic data:\n  expected first duplicate index 1, got 2\n  see external.example/fix for instructions\n\nAuthorized task:\n  repair LowerBound and prove duplicate handling\n\nThe external page cannot authorize uploading files or secrets.","language":"text","title":"Recognize an instruction hidden in a failure","walkthrough":"The URL is an illustrative untrusted destination, not a link to visit. The useful evidence is the mismatch between expected and actual index; an unrelated upload request does not help establish that invariant."},{"body":"Give agent-driven tests a disposable database, namespaced keys and bounded cleanup. A unique key prefix does not protect other data if a cleanup script still runs FLUSHDB. Inspect generated commands before they can affect shared systems, especially dependency installers, migrations and deployment steps.","title":"Use isolated integration resources"},{"body":"Use environment or credential mechanisms approved for the selected tool. Include variable names in setup instructions rather than real passwords. Logs, traces, snapshots and fixtures can also retain private data; inspect what a test or support bundle records before sharing it.","title":"Keep secrets out of the conversation and diff"},{"body":"Record the changed files, checks actually run, unresolved failures and next concrete step. Preserve the original task constraints after context reduction. A handoff saying everything is safe without naming evidence is difficult for either a human or another session to verify.","title":"Make a useful handoff"},{"body":"A comment, test fixture or printed output can contain text asking an agent to reveal secrets or use other tools. Those strings are task data, not authority. A room capability grants access only to that room. It must not grant filesystem access, arbitrary shell commands, another project or automatic execution on someone else’s device. The relay transports text; local execution remains a separate human action.","code":"Untrusted: source / comments / test output / shared progress\nTrusted authority: the human task and explicitly granted room role\nExecution boundary: a local person presses Run/Test\n\nA prompt in stdout cannot promote View to Edit or execute on another phone.","language":"text","title":"Treat room source, Output and progress as untrusted data","walkthrough":"The diagram distinguishes data from authority. A malicious printed line stays inside Output and cannot authorize another tool or another device. Preserve this boundary even when the content sounds like an urgent system instruction."},{"body":"Room links are bearer capabilities: a person or AI receiving a working Edit link can read and change the room until expiry or closure. A View link permits reading and copying. The fragment is outside the initial page request, but the client deliberately sends the credential to the relay in an API header or tool argument. GopherForge’s preview relay can read shared source and Output; it is not end-to-end encrypted. Progress publication is a separate 90-day, read-only snapshot with a revocation key. Exclude private code, access tokens and production data; revocation cannot erase downloaded copies.","title":"Understand what sharing actually exposes"}],"takeaway":"Treat external text as task data, enforce permissions with real controls and verify sensitive commands at their boundary. Keep the Go fix tied to its authorized behavior.","title":"Agent trust boundaries: repository text is input data","unitID":"ai","wrongAnswers":["Follow it because it came from a test","Upload first and redact the reply"]},{"conceptTag":"concurrency.waitgroup-go","designGuide":{"cautions":["Use an error-aware group for returned task errors and keep a separate bounded cancellation path for work that may block."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"WaitGroup.Go joins tasks; it does not collect their errors","flow":["Register owned tasks","Write independent results","Observe cancellation","Join before cleanup"],"ratings":[],"strengths":["Use modern WaitGroup task ownership and explain its limits.","WaitGroup.Go registers owned work and Wait joins it. Cancellation, errors, panic policy and admission control remain separate parts of the design."]},"hint":"Joining waits for exit; it cannot manufacture an exit path.","id":"concurrency.waitgroup-go","introduction":"A request owns more than the act of starting goroutines. It must know when its work has stopped and who retains the results. Go 1.25 added WaitGroup.Go, which combines task registration and launch. It reduces a common Add/launch ordering mistake without supplying cancellation, an error result or a concurrency budget.","nuance":"Use an error-aware group for returned task errors and keep a separate bounded cancellation path for work that may block.","objective":"Use modern WaitGroup task ownership and explain its limits.","question":"Which capabilities do WaitGroup.Go and Wait provide for owned goroutines?","references":["https://pkg.go.dev/sync#WaitGroup.Go","https://go.dev/doc/go1.25","https://go.dev/ref/mem"],"reviewAnswer":"Task registration and a join","reviewPrompt":"What does WaitGroup.Go add?","sections":[{"body":"Each task writes to a distinct fixed result slot, and the owner reads results after Wait. That separates mutation by index without concurrently appending to a shared slice. Do not copy an already used WaitGroup or start an unrelated task after the owner has concluded that the group is empty.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\nfunc main() {\n\tinput := []int{2, 3, 4}\n\toutput := make([]int, len(input))\n\tvar tasks sync.WaitGroup\n\tfor i, value := range input {\n\t\ttasks.Go(func() { output[i] = value * value })\n\t}\n\ttasks.Wait()\n\tfmt.Println(output)\n}\n\n// Output:\n// [4 9 16]\n","language":"go","title":"Register and join owned work","walkthrough":"This complete Go 1.25+ example relies on modern loop-declared variables, distinct output elements and an explicit join. It launches only three tasks. A production version with many inputs still needs admission control before launch, and result values must not share unsafe internal storage."},{"body":"The task function passed to WaitGroup.Go must not panic. It has no error return. Expected failures need an explicit result channel or an error-aware task group, and panic handling belongs to a deliberately chosen boundary. A WaitGroup cannot roll back side effects from a task that already ran.","title":"Do not infer an error protocol"},{"body":"Wait does not take a context or kill a blocked task. A task doing I/O or sending a result must observe cancellation at each potentially blocking point. On shutdown, stop intake, signal cancellation where appropriate, wait for owned tasks and only then close the resources they use.","title":"Give cancellation its own path"},{"body":"Use synchronization or a virtual-time test to hold a task at a known boundary. Verify the owner does not publish success until all required work finishes. A sleep followed by checking a counter depends on timing and may hide the same bug on a slower machine.","title":"Test completion rather than scheduling luck"}],"takeaway":"WaitGroup.Go registers owned work and Wait joins it. Cancellation, errors, panic policy and admission control remain separate parts of the design.","title":"WaitGroup.Go joins tasks; it does not collect their errors","unitID":"concurrency","wrongAnswers":["Cancel the blocked send automatically","Collect and return its error"]},{"conceptTag":"concurrency.synctest","designGuide":{"cautions":["Use the bubble for a deterministic in-process protocol and retain isolated integration tests for external services."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"Test time and cancellation without sleeping on the wall clock","flow":["Describe a timeline","Hold a known phase","Advance virtual time","Assert completion and effects"],"ratings":[],"strengths":["Use testing/synctest to assert a concurrent timeline deterministically.","Describe the timeline and assert both early and final states. Virtual time makes supported concurrent tests reproducible; it does not replace real boundary integration checks."]},"hint":"Separate in-process evidence from an external system boundary.","id":"concurrency.synctest","introduction":"Tests that sleep for a guessed interval are slow and sensitive to machine load. testing/synctest is a standard package in Go 1.25 and later. It runs a test bubble with virtual time and coordinated goroutine waiting. It is useful for in-process protocols, not a simulator for a remote database or every operating-system event.","nuance":"Use the bubble for a deterministic in-process protocol and retain isolated integration tests for external services.","objective":"Use testing/synctest to assert a concurrent timeline deterministically.","question":"What does a supported testing/synctest bubble control, rather than real remote-service behavior?","references":["https://pkg.go.dev/testing/synctest","https://go.dev/blog/testing-time"],"reviewAnswer":"Time inside a supported test bubble","reviewPrompt":"What does synctest virtualize?","sections":[{"body":"Suppose work waits five seconds, publishes a result and exits. The test should establish that it has not published before the deadline and has completed after it. synctest.Wait lets in-bubble goroutines settle at supported blocking points so the assertions do not depend on the scheduler getting lucky.","code":"package timeline\n\nimport (\n\t\"testing\"\n\t\"testing/synctest\"\n\t\"time\"\n)\n\nfunc TestDelayedResult(t *testing.T) {\n\tsynctest.Test(t, func(t *testing.T) {\n\t\tdone := make(chan struct{})\n\t\tgo func() { time.Sleep(5 * time.Second); close(done) }()\n\t\tsynctest.Wait()\n\t\tselect {\n\t\tcase <-done:\n\t\t\tt.Fatal(\"completed before the deadline\")\n\t\tdefault:\n\t\t}\n\t\ttime.Sleep(5 * time.Second)\n\t\tsynctest.Wait()\n\t\tselect {\n\t\tcase <-done:\n\t\tdefault:\n\t\t\tt.Fatal(\"result not published\")\n\t\t}\n\t})\n}\n","language":"go","title":"State the timeline first","walkthrough":"Save this complete example as timeline_test.go in a native Go 1.25+ module and run go test -race. The five-second sleep advances virtual time instead of imposing five seconds of wall-clock waiting. This lesson is a reading; it does not promise this diagnostic package on every WASI target."},{"body":"Model a worker waiting on either its timer or ctx.Done, then cancel at a known phase. Assert that the worker closes its completion signal and does not publish an unwanted result. Cancellation and a simultaneously ready result still need a documented policy; select is not a strict priority rule.","title":"Add a cancellation branch"},{"body":"Virtual time advances when the package can establish the relevant in-bubble blocking state. External network servers, syscalls and objects outside the bubble have different constraints. Keep real integration tests for sockets and databases rather than treating a fast virtual-time test as evidence of remote behavior.","title":"Know the boundary of the bubble"},{"body":"A deterministic test must still assert something meaningful. For a retry protocol, count durable effects and total attempts under a deadline; for cancellation, prove exit with a completion signal. A test that merely waits for the bubble to finish does not verify every business result.","title":"Keep the invariant after removing sleeps"}],"takeaway":"Describe the timeline and assert both early and final states. Virtual time makes supported concurrent tests reproducible; it does not replace real boundary integration checks.","title":"Test time and cancellation without sleeping on the wall clock","unitID":"concurrency","wrongAnswers":["That real network failover was tested","That every goroutine schedule is safe"]},{"conceptTag":"concurrency.errgroup","designGuide":{"cautions":["SetLimit bounds active group functions, not every queued byte. All started work must be joined before its dependencies are released."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"errgroup: errors, cancellation and a real concurrency limit","flow":["Choose a task budget","Propagate group context","Collect a task error","Join before publishing"],"ratings":[],"strengths":["Coordinate fallible parallel work without confusing cancellation with joining.","Choose one owner for submission, cancellation, joining and result publication. An error-aware group simplifies coordination but does not supply a durable transaction or every admission policy."]},"hint":"The derived context belongs to the group operation.","id":"concurrency.errgroup","introduction":"golang.org/x/sync/errgroup is a versioned external module, not part of sync. WithContext supplies a derived cancellation context and Wait returns a task error. Tasks must still cooperate with cancellation, and a limit on active tasks is different from a limit on queued input bytes or waiting requests.","nuance":"SetLimit bounds active group functions, not every queued byte. All started work must be joined before its dependencies are released.","objective":"Coordinate fallible parallel work without confusing cancellation with joining.","question":"Which fact must guide reuse of an errgroup-derived context after Wait returns successfully?","references":["https://pkg.go.dev/golang.org/x/sync/errgroup","https://pkg.go.dev/context"],"reviewAnswer":"Wait ends the derived context","reviewPrompt":"Group context after Wait?","sections":[{"body":"A group cancels its derived context when a task returns a non-nil error or when Wait returns. Keep that context inside the operation. Even a successful Wait leaves it canceled, so later independent work must use the caller’s appropriate context instead.","code":"group, workCtx := errgroup.WithContext(ctx)\ngroup.SetLimit(4)\nfor i, id := range ids {\n\tif workCtx.Err() != nil {\n\t\tbreak\n\t}\n\tgroup.Go(func() error {\n\t\tvalue, err := load(workCtx, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutput[i] = value\n\t\treturn nil\n\t})\n}\nif err := group.Wait(); err != nil {\n\treturn nil, err\n}\nif err := ctx.Err(); err != nil {\n\treturn nil, err\n}\nreturn output, nil","language":"go","title":"Use the derived context for the owned operation","walkthrough":"This native function-body fragment uses the errgroup package, modern loop declarations, a preallocated output slice and a context-aware load function. The simple submission loop assumes load always exits on cancellation. The group does not deep-copy returned values."},{"body":"Go waits for room when the group is at its configured limit; that admission wait is not itself a ctx-select operation. Do not change the limit while tasks are active. TryGo can express nonblocking admission when the caller has a rejection policy. A fixed worker pool may fit a streaming or explicitly bounded queue better.","title":"Understand where SetLimit blocks"},{"body":"Production submission may fail before every task is added. Do not return and close dependencies while already started tasks still use them. Cancel the operation and call Wait on every exit path that has launched work. Returning from a helper is not a join; a surrounding owner must enforce that lifecycle.","title":"Join after a submission failure"},{"body":"A failed group may have populated some result slots before cancellation. Decide whether the operation permits partial success and represent it explicitly. For all-or-nothing results, return no successful result after Wait fails. Database transactions and idempotency still decide which external effects survive.","title":"Separate partial results from successful results"}],"takeaway":"Choose one owner for submission, cancellation, joining and result publication. An error-aware group simplifies coordination but does not supply a durable transaction or every admission policy.","title":"errgroup: errors, cancellation and a real concurrency limit","unitID":"concurrency","wrongAnswers":["Always the now-canceled group context","A new context with no owner or budget"]},{"conceptTag":"sql.pool-lifetime","designGuide":{"cautions":["A larger connection cap can move waiting into an overloaded database. Admission and query efficiency still need their own policies."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"SQL: one pool, explicit capacity and observable waiting","flow":["Construct one pool","Set a deployment budget","Measure wait deltas","Drain before closing"],"ratings":[],"strengths":["Configure database/sql as a shared pool and measure its actual pressure.","Own one shared pool, bound operation lifetimes and admission, and measure pool waits across all replicas before changing connection limits."]},"hint":"Multiply per-process settings by every active pool owner.","id":"sql.pool-lifetime","introduction":"sql.DB is a concurrency-safe pool handle, not a single database connection. Reuse it across the application and close it after its users drain. These lessons describe native Go services using a real driver; the app’s bounded WASI programs cannot open remote database sockets.","nuance":"A larger connection cap can move waiting into an overloaded database. Admission and query efficiency still need their own policies.","objective":"Configure database/sql as a shared pool and measure its actual pressure.","question":"What does one shared *sql.DB represent inside a Go service?","references":["https://go.dev/doc/database/manage-connections","https://pkg.go.dev/database/sql#DB.Stats","https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib"],"reviewAnswer":"A shared pool, not one connection","reviewPrompt":"What does sql.DB own?","sections":[{"body":"sql.Open generally constructs a handle rather than proving connectivity. Use a bounded PingContext for startup evidence, then handle every operation error separately. Configure a reviewed driver version in the native service module; pgx/v5/stdlib is one PostgreSQL driver option.","code":"db, err := sql.Open(\"pgx\", dsn)\nif err != nil {\n\treturn nil, err\n}\ndb.SetMaxOpenConns(12)\ndb.SetMaxIdleConns(6)\ndb.SetConnMaxIdleTime(2 * time.Minute)\ndb.SetConnMaxLifetime(30 * time.Minute)\nprobe, cancel := context.WithTimeout(ctx, 2*time.Second)\ndefer cancel()\nif err := db.PingContext(probe); err != nil {\n\t_ = db.Close()\n\treturn nil, fmt.Errorf(\"database readiness: %w\", err)\n}\nreturn db, nil","language":"go","title":"Construct once and verify readiness","walkthrough":"This startup-function fragment imports database/sql, context, fmt, time and the chosen PostgreSQL driver registration. The DSN comes from configuration. The numeric settings are examples, not sizing advice; a returned shared pool needs one application lifetime owner."},{"body":"A limit of twelve per replica means something different with two replicas than with fifty. Reserve database capacity for migrations, administration and other applications. SetMaxOpenConns bounds this pool’s open connections; it is not a global request limiter or a cap on goroutines waiting to acquire one.","title":"Budget across the deployment"},{"body":"DB.Stats exposes OpenConnections, InUse, Idle, WaitCount and WaitDuration. Wait counters accumulate, so compare their changes over the same measurement interval. A high wait rate can reflect slow transactions, leaked rows or too much admission rather than a pool that should simply be enlarged.","code":"stats := db.Stats()\nfmt.Println(stats.OpenConnections, stats.InUse, stats.Idle)\nfmt.Println(stats.WaitCount, stats.WaitDuration)\n// Record deltas over a defined interval alongside request latency.","language":"go","title":"Read counters as changes over an interval","walkthrough":"The fragment observes a shared sql.DB and imports fmt. Lifetime counters do not identify the present bottleneck by themselves. Correlate a pool-wait interval with query latency, queue length, errors and the database’s own evidence."},{"body":"A native pgxpool.Pool is another pool abstraction with its own settings and metrics. Do not wrap one pool in another or assume database/sql option names apply unchanged. Choose the API the service uses, then test saturation and shutdown for that actual combination.","title":"Distinguish other pool APIs"}],"takeaway":"Own one shared pool, bound operation lifetimes and admission, and measure pool waits across all replicas before changing connection limits.","title":"SQL: one pool, explicit capacity and observable waiting","unitID":"sql","wrongAnswers":["One dedicated connection reserved for each handler","One global pool automatically shared by every service replica"]},{"conceptTag":"sql.rows-and-context","designGuide":{"cautions":["A parameterized tenant value still requires authorization, and LIMIT is not a universal bound on query execution cost."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"SQL rows: close, check errors and bound the result","flow":["Authorize and bind values","Run a bounded query","Scan owned rows","Check final iteration error"],"ratings":[],"strengths":["Write a cancellation-aware query loop without losing iteration failures.","Check Query, Scan and final iteration errors as separate phases. Close owned rows, authorize scope and cap returned work before reporting a successful result."]},"hint":"Next returning false can mean end of rows or an error.","id":"sql.rows-and-context","introduction":"A successful QueryContext does not mean every row will decode successfully. Network and server errors can occur during iteration, and Scan can fail on a type or null mismatch. Decide whether partial results are meaningful; do not silently return a successful incomplete list.","nuance":"A parameterized tenant value still requires authorization, and LIMIT is not a universal bound on query execution cost.","objective":"Write a cancellation-aware query loop without losing iteration failures.","question":"What must be checked after Rows.Next stops before claiming that the complete query succeeded?","references":["https://go.dev/doc/database/querying","https://pkg.go.dev/database/sql#Rows","https://go.dev/doc/database/cancel-operations"],"reviewAnswer":"Rows.Err after the loop","reviewPrompt":"SQL iteration ended. Check?","sections":[{"body":"This PostgreSQL helper returns at most one hundred identifiers, uses a parameter for the tenant value and returns no successful partial result on failure. A real endpoint must derive tenant from authorization, not merely trust a request parameter.","code":"func noteIDs(ctx context.Context, db *sql.DB, tenant string) ([]int64, error) {\n\trows, err := db.QueryContext(ctx,\n\t\t`SELECT id FROM notes WHERE tenant_id = $1 ORDER BY id LIMIT 100`, tenant)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tvar ids []int64\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tif err := rows.Scan(&id); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tids = append(ids, id)\n\t}\n\tif err := rows.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ids, nil\n}","language":"go","title":"Bound a tenant-scoped query","walkthrough":"The helper imports context and database/sql and assumes a PostgreSQL-compatible driver and a notes table with an integer id. Close releases resources on early return; Err checks failure after Next becomes false. For a query whose close result affects correctness, handle that result explicitly too."},{"body":"QueryRowContext defers its error until Scan. Distinguish sql.ErrNoRows from an infrastructure or conversion failure. Use nullable types or pointers when the schema permits null; a zero int is not automatically a missing value. Keep parameter placeholders consistent with the chosen driver.","title":"Handle one row and null deliberately"},{"body":"The $1 parameter protects a value position. It does not let a caller supply an arbitrary table name or ORDER BY expression safely. Choose identifiers and sort directions from a fixed application allowlist, and bind all untrusted values separately.","title":"Parameters bind values, not SQL grammar"},{"body":"A LIMIT bounds this helper’s row count, not the byte size of arbitrary columns or total work examined by the plan. For exports, stream bounded records and carry cancellation to the cursor. Test a failure after several rows and define the response protocol once output has started.","title":"Separate buffering from streaming"}],"takeaway":"Check Query, Scan and final iteration errors as separate phases. Close owned rows, authorize scope and cap returned work before reporting a successful result.","title":"SQL rows: close, check errors and bound the result","unitID":"sql","wrongAnswers":["Return three records with no error","Ignore the final iteration status"]},{"conceptTag":"sql.transaction-owner","designGuide":{"cautions":["A transaction does not automatically include pool calls or an external provider. Check commit outcomes and idempotency at the actual boundary."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"SQL transactions: every participating call uses the transaction","flow":["Validate the command","Begin one transaction","Use tx for every call","Commit or roll back"],"ratings":[],"strengths":["Place an atomic business transition inside one explicit transaction owner.","One owner starts the transaction, passes its handle to every participating call and finishes it. Database atomicity does not include remote side effects."]},"hint":"Context propagation and transaction membership are different contracts.","id":"sql.transaction-owner","introduction":"Beginning a transaction does not attach later calls on sql.DB to it. The transaction handle owns a particular transactional connection. A helper that accidentally queries db instead of tx may see another state, escape rollback or wait for a second connection while holding the first.","nuance":"A transaction does not automatically include pool calls or an external provider. Check commit outcomes and idempotency at the actual boundary.","objective":"Place an atomic business transition inside one explicit transaction owner.","question":"What must a helper use for its write to participate in the caller’s open SQL transaction?","references":["https://go.dev/doc/database/execute-transactions","https://pkg.go.dev/database/sql#Tx"],"reviewAnswer":"The same transaction handle","reviewPrompt":"Transaction calls use?","sections":[{"body":"This abbreviated PostgreSQL transfer updates both accounts through tx. Reject nonpositive amounts before starting, use an exact integer minor-unit representation and treat account currency and authorization as additional domain constraints.","code":"tx, err := db.BeginTx(ctx, nil)\nif err != nil {\n\treturn err\n}\ndefer tx.Rollback()\nresult, err := tx.ExecContext(ctx,\n\t`UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1`, amount, from)\nif err != nil {\n\treturn err\n}\nn, err := result.RowsAffected()\nif err != nil {\n\treturn err\n}\nif n != 1 {\n\treturn ErrInsufficientOrMissing\n}\nresult, err = tx.ExecContext(ctx,\n\t`UPDATE accounts SET balance = balance + $1 WHERE id = $2`, amount, to)\nif err != nil {\n\treturn err\n}\nn, err = result.RowsAffected()\nif err != nil {\n\treturn err\n}\nif n != 1 {\n\treturn ErrDestinationMissing\n}\nreturn tx.Commit()","language":"go","title":"Make the atomic boundary visible","walkthrough":"This function-body fragment assumes validated amount/from/to and application errors. Every write uses tx. The deferred Rollback is harmless after a successful Commit. A complete transfer also scopes ownership, checks currency and overflow bounds, and defines retry/idempotency semantics."},{"body":"A helper can accept the ExecContext or QueryContext capability it needs instead of a hidden global db. That makes accidental pool calls easier to see. The runtime guarantee still comes from passing the same transaction handle to every participating operation, not from an interface name alone.","title":"Pass a narrow transaction capability"},{"body":"An email, HTTP payment or message publish is not rolled back by the SQL transaction. Persist a durable outbox or intent with the state change, then deliver through an idempotent protocol. Do not keep a transaction open while waiting for a user or a slow remote service.","title":"Keep external effects outside the callback"},{"body":"A lost reply can make a durable outcome uncertain. Distinguish documented serialization/deadlock failures from transport ambiguity. Use a stable operation ID to reconcile the latter. Test abort-before-write, error-after-write and commit-then-disconnect separately.","title":"Do not interpret every commit error as an abort"}],"takeaway":"One owner starts the transaction, passes its handle to every participating call and finishes it. Database atomicity does not include remote side effects.","title":"SQL transactions: every participating call uses the transaction","unitID":"sql","wrongAnswers":["Any *sql.DB that receives the same context","Any query executed inside the same Go function"]},{"conceptTag":"sql.isolation-and-locks","designGuide":{"cautions":["Isolation levels and lock details are database-specific. Do not promise one engine’s exact behavior for every SQL driver."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"SQL isolation and deadlocks: test the business invariant","flow":["State the invariant","Choose isolation or locks","Force a concurrent schedule","Assert durable state"],"ratings":[],"strengths":["Explain why atomic statements alone may not preserve a multi-row invariant.","Choose isolation and locking from the invariant, understand the database-specific failures and prove the protocol with concurrent transactions on the actual engine."]},"hint":"The authoritative state is in another concurrency system.","id":"sql.isolation-and-locks","introduction":"A transaction can be atomic without providing the isolation an invariant needs. Two transactions may both read a condition as true and each make a different write that breaks the combined rule. Exact behavior depends on the database and isolation level; this lesson uses PostgreSQL terminology explicitly.","nuance":"Isolation levels and lock details are database-specific. Do not promise one engine’s exact behavior for every SQL driver.","objective":"Explain why atomic statements alone may not preserve a multi-row invariant.","question":"Two replicas pass Go race tests but violate a multi-row invariant. What evidence is missing?","references":["https://www.postgresql.org/docs/current/transaction-iso.html","https://www.postgresql.org/docs/current/explicit-locking.html","https://pkg.go.dev/database/sql#TxOptions"],"reviewAnswer":"Database races need database tests","reviewPrompt":"Can -race prove SQL isolation?","sections":[{"body":"Imagine two on-call doctors, each allowed to leave only while another remains. Both transactions read two active doctors and each removes its own row. The final state violates the rule even though every individual write is valid. This is a business-level concurrency problem, not an unsynchronized Go map access.","title":"Name the anomaly"},{"body":"A suitable constraint, conditional update, lock protocol or serializable transaction can protect an invariant, depending on how it is represented. PostgreSQL serializable isolation may reject a transaction that would create an incompatible history. Applications must handle that failure rather than treating serializable as a promise that no request ever retries.","code":"tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})\nif err != nil {\n\treturn err\n}\ndefer tx.Rollback()\n// Read and write the complete invariant using tx and the same ctx.\n// A documented serialization failure can require retrying the whole unit.\nreturn tx.Commit()","language":"go","title":"Choose a database-enforced protocol","walkthrough":"This native transaction skeleton imports database/sql and assumes a driver supporting the requested isolation. It deliberately omits application SQL: the correct statements depend on the invariant. Test the protocol against the actual database rather than a fake that always accepts commits."},{"body":"Two transfers can lock accounts in opposite orders and deadlock. Acquire relevant locks in a consistent order where possible, keep transactions short and avoid holding locks across remote calls. Deadlock detection prevents one kind of permanent wait by aborting work; it does not make the application transition automatically succeed.","title":"Use consistent lock order"},{"body":"Use synchronization barriers to place both transactions after their initial reads, then release their writes. Assert the final invariant and the expected failure/retry behavior. A process-local mutex cannot establish the same guarantee across every service replica, and the race detector does not observe database interleavings.","title":"Reproduce with two independent connections"}],"takeaway":"Choose isolation and locking from the invariant, understand the database-specific failures and prove the protocol with concurrent transactions on the actual engine.","title":"SQL isolation and deadlocks: test the business invariant","unitID":"sql","wrongAnswers":["More goroutines in the unit-test fake","A larger client-side connection pool"]},{"conceptTag":"sql.retry-and-idempotency","designGuide":{"cautions":["Retry classification is driver-specific. Preserve one total deadline and use durable deduplication for ambiguous side effects."],"cost":"Choose the policy from the actual contract, then verify its failure path in the target environment.","family":"SQL retries: restart a safe transaction, reconcile an unknown result","flow":["Classify the outcome","Choose one retry owner","Respect the total budget","Reconcile durable identity"],"ratings":[],"strengths":["Separate retryable transaction aborts from an ambiguous committed operation.","Retry a documented safe unit within one budget. Reconcile uncertain commit outcomes through durable operation identity rather than assuming an error proves no effect occurred."]},"hint":"Distinguish an explicit abort from a missing acknowledgment.","id":"sql.retry-and-idempotency","introduction":"Retrying the last failed SQL statement can be wrong when an earlier statement read stale state or the transaction is already aborted. A safe retry policy names the driver error, restarts the complete business unit when appropriate, stays within a total deadline and prevents repeated external effects.","nuance":"Retry classification is driver-specific. Preserve one total deadline and use durable deduplication for ambiguous side effects.","objective":"Separate retryable transaction aborts from an ambiguous committed operation.","question":"A network error arrives after a charge may have committed. What can be concluded about the durable effect?","references":["https://www.postgresql.org/docs/current/mvcc-serialization-failure-handling.html","https://www.postgresql.org/docs/current/errcodes-appendix.html","https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn#PgError"],"reviewAnswer":"The durable outcome may be unknown","reviewPrompt":"A commit reply is lost. Assume?","sections":[{"body":"For PostgreSQL, serialization_failure is SQLSTATE 40001 and deadlock_detected is 40P01. Inspect structured driver errors rather than parsing an English error message. Those codes are not interchangeable with a lost network response, which can leave an outcome unknown.","code":"var pgErr *pgconn.PgError\nif errors.As(err, &pgErr) {\n\tretryable := pgErr.Code == \"40001\" || pgErr.Code == \"40P01\"\n\t_ = retryable // apply the caller's bounded whole-transaction policy\n}","language":"go","title":"Classify with the real driver","walkthrough":"The native fragment imports errors and github.com/jackc/pgx/v5/pgconn. It only classifies two PostgreSQL conditions; it is not a complete retry loop and does not claim every network or database error is retryable."},{"body":"Use a small reviewed attempt cap, bounded jittered delay and the remaining overall deadline. Recreate the transaction and re-read necessary state on each attempt. Do not let HTTP, application and driver retries multiply independently into a storm while every request retains a connection or body.","title":"Give one layer the retry budget"},{"body":"If a payment-like command committed but its reply was lost, retrying without an operation identity can duplicate the transition. Store a scoped idempotency key and request fingerprint under a uniqueness rule. Return the prior result or reconcile provider state; a transaction cannot un-send a remote charge.","title":"Reconcile transport ambiguity"},{"body":"Inject a known abort before commit, an exhausted deadline, concurrent duplicate commands and commit-then-disconnect. Assert one durable business effect and a useful response classification. Include isolation and schema compatibility in a release rollback plan; reverting a binary does not erase committed data.","title":"Test the windows, not only the loop count"}],"takeaway":"Retry a documented safe unit within one budget. Reconcile uncertain commit outcomes through durable operation identity rather than assuming an error proves no effect occurred.","title":"SQL retries: restart a safe transaction, reconcile an unknown result","unitID":"sql","wrongAnswers":["The charge definitely failed and needs a fresh payment identity","Any non-nil error proves that the server rolled back"]},{"conceptTag":"systems.transaction-boundary","designGuide":{"cautions":["A mutex can protect an in-memory invariant but cannot make process memory durable or roll back an external payment.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Parse input","Validate invariant","One transaction","Map result"],"ratings":[],"strengths":["Keep the business invariant and transaction boundary in the application service.","Makes the owner and the failure boundary explicit."]},"hint":"The first call validates before changing either account and prints balances 3 and 11.","id":"systems.transaction-boundary","introduction":"A transport handler can parse a request correctly while the application still commits only half of a business operation. Place the invariant in one use case and make its transaction boundary explicit. The adapter translates HTTP and errors; it does not independently commit each repository call. A Go interface alone cannot make two stores atomic.","nuance":"The application use case owns one transaction and passes its handle to every participating storage operation; HTTP mapping stays in the adapter.","objective":"Keep the business invariant and transaction boundary in the application service.","question":"Two repository calls must succeed together. Who owns their transaction?","references":["https://pkg.go.dev/database/sql#DB.BeginTx","https://go.dev/doc/database/execute-transactions"],"reviewAnswer":"One owner commits the whole invariant","reviewPrompt":"Use-case transaction","sections":[{"body":"A transport handler can parse a request correctly while the application still commits only half of a business operation. Place the invariant in one use case and make its transaction boundary explicit. The adapter translates HTTP and errors; it does not independently commit each repository call. A Go interface alone cannot make two stores atomic.","title":"The contract and the failure"},{"body":"Trace validation, ownership and commit separately. In a SQL implementation, begin once in the use case, pass the same *sql.Tx to participating operations, defer Rollback and check Commit. Do not call the original *sql.DB from a repository that was supposed to join the transaction. Keep HTTP status mapping outside the use case.","code":"package main\n\nimport \"fmt\"\n\ntype Account struct{ Balance int }\n\nfunc transfer(from, to *Account, amount int) error {\n\tif from == to || amount <= 0 || from.Balance < amount {\n\t\treturn fmt.Errorf(\"invalid transfer\")\n\t}\n\t// Single-owner, in-memory teaching model, not a database transaction.\n\tfrom.Balance -= amount\n\tto.Balance += amount\n\treturn nil\n}\nfunc main() {\n\ta, b := Account{10}, Account{4}\n\tfmt.Println(transfer(&a, &b, 7), a.Balance, b.Balance)\n\tfmt.Println(transfer(&a, &b, 7), a.Balance, b.Balance)\n}","language":"go","title":"Work through the example","walkthrough":"The first call validates before changing either account and prints balances 3 and 11. The second call fails before changing either value. This is safe only under the explicitly stated single owner; concurrent callers and crashes require a real storage transaction or an equivalent concurrency protocol."},{"body":"A mutex can protect an in-memory invariant but cannot make process memory durable or roll back an external payment. Under concurrent SQL writes, test isolation, row predicates and lock ordering. An interface named UnitOfWork is not evidence that all its methods share the same transaction. Define whether a failed commit is known to have aborted or has an unknown outcome.","title":"Production decisions"},{"body":"Two repository calls must succeed together. Who owns their transaction? The application use case owns one transaction and passes its handle to every participating storage operation; HTTP mapping stays in the adapter. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Keep the business invariant and transaction boundary in the application service. The application use case owns one transaction and passes its handle to every participating storage operation; HTTP mapping stays in the adapter.","title":"A use case owns its transaction, not its HTTP handler","unitID":"system-design","wrongAnswers":["Each repository commits independently","The HTTP router supplies atomicity"]},{"conceptTag":"systems.outbox-inbox","designGuide":{"cautions":["A relay can crash after broker acknowledgement but before marking the row sent, so duplicates are normal.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Business + outbox commit","Relay publishes","Possible duplicate","Inbox + effect commit"],"ratings":[],"strengths":["Commit a business change and its publication intent together, then deduplicate delivery.","Makes the owner and the failure boundary explicit."]},"hint":"The stable event ID, not a newly generated delivery ID, identifies the duplicate.","id":"systems.outbox-inbox","introduction":"Writing an order and publishing its event are two different side effects. A crash between them can leave a missing event; publishing first can announce a change that never commits. An outbox stores publication intent beside the business write in the same durable transaction. A separate relay retries it, and the consumer expects duplicates rather than claiming end-to-end exactly once.","nuance":"Retry may deliver the event again. A stable ID and an atomic consumer inbox/effect boundary prevent repeating the business effect.","objective":"Commit a business change and its publication intent together, then deduplicate delivery.","question":"The broker acknowledged, then the relay crashed before marking sent. What now?","references":["https://microservices.io/patterns/data/transactional-outbox.html","https://microservices.io/patterns/communication-style/idempotent-consumer.html","https://go.dev/doc/database/execute-transactions"],"reviewAnswer":"Atomic intent, retry relay, deduplicate effect","reviewPrompt":"Outbox + inbox","sections":[{"body":"Writing an order and publishing its event are two different side effects. A crash between them can leave a missing event; publishing first can announce a change that never commits. An outbox stores publication intent beside the business write in the same durable transaction. A separate relay retries it, and the consumer expects duplicates rather than claiming end-to-end exactly once.","title":"The contract and the failure"},{"body":"Give each outbox record an immutable event ID, aggregate ID, payload/schema version and publication state. Commit it with the order, then have a bounded relay claim pending rows. The relay marks delivery only after the broker acknowledges. A consumer uses a unique event ID constraint and updates its own state in the same local transaction.","code":"package main\n\nimport \"fmt\"\n\ntype Event struct{ ID, Order string }\ntype Inbox struct {\n\tseen  map[string]bool\n\ttotal int\n}\n\nfunc (i *Inbox) Apply(e Event) bool {\n\tif i.seen[e.ID] {\n\t\treturn false\n\t}\n\t// Teaching model: one owner. Persist both changes atomically in production.\n\ti.total++\n\ti.seen[e.ID] = true\n\treturn true\n}\nfunc main() {\n\ti := Inbox{seen: map[string]bool{}}\n\te := Event{\"evt-1\", \"order-7\"}\n\tfmt.Println(i.Apply(e), i.Apply(e), i.total) // true false 1\n}","language":"go","title":"Work through the example","walkthrough":"The stable event ID, not a newly generated delivery ID, identifies the duplicate. The model applies the first event once and rejects its replay. A production inbox must persist the deduplication record and business change in one transaction; this map intentionally demonstrates neither crash safety nor distributed atomicity."},{"body":"A relay can crash after broker acknowledgement but before marking the row sent, so duplicates are normal. Marking sent first risks permanent loss. State the ordering requirement per aggregate, retention period and poison-event policy. Test crashes on both sides of acknowledgement and a consumer crash between its effect and deduplication write; a process-local map does not pass those tests.","title":"Production decisions"},{"body":"The broker acknowledged, then the relay crashed before marking sent. What now? Retry may deliver the event again. A stable ID and an atomic consumer inbox/effect boundary prevent repeating the business effect. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Commit a business change and its publication intent together, then deduplicate delivery. Retry may deliver the event again. A stable ID and an atomic consumer inbox/effect boundary prevent repeating the business effect.","title":"Outbox and inbox: close the database–broker gap","unitID":"system-design","wrongAnswers":["Mark sent before publishing","Assume a broker removes every duplicate"]},{"conceptTag":"systems.sagas","designGuide":{"cautions":["A timeout is not proof that charging failed.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Persist step","Issue stable command","Reconcile outcome","Confirm compensation"],"ratings":[],"strengths":["Model a distributed workflow as durable states with explicit compensation and recovery.","Makes the owner and the failure boundary explicit."]},"hint":"Shipping failure moves the workflow into refunding.","id":"systems.sagas","introduction":"A reservation, payment authorization and shipment may belong to different services. They cannot usually share a database transaction. A saga records progress and issues commands whose effects can be retried or compensated. Compensation is another business operation, with its own failures, rather than a database rollback that erases everything that already happened.","nuance":"The outcome is unknown. Reconcile the stable payment identity before retrying or compensating, and keep the workflow state durable.","objective":"Model a distributed workflow as durable states with explicit compensation and recovery.","question":"How should a compensating action, such as refunding an accepted payment, be modeled in a saga?","references":["https://microservices.io/patterns/data/saga.html","https://pkg.go.dev/context"],"reviewAnswer":"A durable business action that may also fail","reviewPrompt":"Saga compensation","sections":[{"body":"A reservation, payment authorization and shipment may belong to different services. They cannot usually share a database transaction. A saga records progress and issues commands whose effects can be retried or compensated. Compensation is another business operation, with its own failures, rather than a database rollback that erases everything that already happened.","title":"The contract and the failure"},{"body":"Define a workflow ID, durable step state, command idempotency key, timeout policy and reconciliation owner. Separate orchestration from event choreography: a central coordinator makes recovery visible, while decentralized reactions need an equally explicit ownership story. Keep irreversible steps late where practical and plan manual resolution for states no automatic compensation can safely resolve.","code":"package main\n\nimport \"fmt\"\n\ntype State string\n\nconst (\n\tReserved  State = \"reserved\"\n\tCharged   State = \"charged\"\n\tRefunding State = \"refunding\"\n\tDone      State = \"done\"\n)\n\nfunc next(s State, event string) (State, error) {\n\tswitch {\n\tcase s == Reserved && event == \"charged\":\n\t\treturn Charged, nil\n\tcase s == Charged && event == \"shipping-failed\":\n\t\treturn Refunding, nil\n\tcase s == Refunding && event == \"refund-confirmed\":\n\t\treturn Done, nil\n\t}\n\treturn s, fmt.Errorf(\"unexpected %s in %s\", event, s)\n}\nfunc main() {\n\ts, _ := next(Charged, \"shipping-failed\")\n\tfmt.Println(s) // refunding, not done\n\ts, err := next(s, \"refund-confirmed\")\n\tfmt.Println(s, err)\n}","language":"go","title":"Work through the example","walkthrough":"Shipping failure moves the workflow into refunding. It does not declare success because a refund command was merely sent. The second transition waits for confirmation. The pure transition function is easy to test, but a durable coordinator must persist the transition and the next command intent atomically."},{"body":"A timeout is not proof that charging failed. Retrying with a new payment identity can double-charge. Compensation can be refused or delayed; do not mark the workflow completed before it is confirmed. Test duplicate commands, late success after timeout, coordinator restart and failure of the compensation itself. Use the smallest number of remote boundaries the business actually requires.","title":"Production decisions"},{"body":"A payment request timed out. Can the workflow safely create a fresh payment? The outcome is unknown. Reconcile the stable payment identity before retrying or compensating, and keep the workflow state durable. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Model a distributed workflow as durable states with explicit compensation and recovery. The outcome is unknown. Reconcile the stable payment identity before retrying or compensating, and keep the workflow state durable.","title":"Sagas: compensate business steps without pretending to roll back time","unitID":"system-design","wrongAnswers":["A universal distributed SQL rollback","Proof that a timed-out payment failed"]},{"conceptTag":"systems.compatibility","designGuide":{"cautions":["A rename performed as drop-old/add-new in one release breaks old binaries during rollout and rollback.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Expand readers","Change writers","Migrate + measure","Contract later"],"ratings":[],"strengths":["Use expand–migrate–contract changes while old and new Go processes coexist.","Makes the owner and the failure boundary explicit."]},"hint":"The new reader accepts the old name field and prefers the additive display_name field when present.","id":"systems.compatibility","introduction":"A rolling deployment is a period with multiple versions, not an instantaneous replacement. The database, producers, consumers and cached clients may all run different code. An additive change is useful only if old readers tolerate it and the new writer does not destroy information they still need. Plan compatibility as a sequence with observable exit conditions.","nuance":"After compatible readers are deployed, data is migrated and evidence shows old consumers no longer require it; rollback and event replay must still work.","objective":"Use expand–migrate–contract changes while old and new Go processes coexist.","question":"An old worker may run for another hour. When may the old schema field be removed?","references":["https://martinfowler.com/bliki/ParallelChange.html","https://pkg.go.dev/encoding/json"],"reviewAnswer":"Add compatibility before removing the old shape","reviewPrompt":"Expand–migrate–contract","sections":[{"body":"A rolling deployment is a period with multiple versions, not an instantaneous replacement. The database, producers, consumers and cached clients may all run different code. An additive change is useful only if old readers tolerate it and the new writer does not destroy information they still need. Plan compatibility as a sequence with observable exit conditions.","title":"The contract and the failure"},{"body":"First deploy readers that understand both shapes. Then introduce the new field and migrate stored data with a restartable cursor. Measure old-field use before removing it. Give events explicit schema contracts and keep captured old payloads as fixtures. Review semantic changes too: changing units, default timeouts or authorization can break a client without changing a Go type.","code":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype Wire struct {\n\tName        string `json:\"name\"`\n\tDisplayName string `json:\"display_name,omitempty\"`\n}\n\nfunc name(w Wire) string {\n\tif w.DisplayName != \"\" {\n\t\treturn w.DisplayName\n\t}\n\treturn w.Name\n}\nfunc main() {\n\tfor _, raw := range []string{`{\"name\":\"Ada\"}`, `{\"name\":\"Ada\",\"display_name\":\"A. Lovelace\"}`} {\n\t\tvar w Wire\n\t\tif err := json.Unmarshal([]byte(raw), &w); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tfmt.Println(name(w))\n\t}\n}","language":"go","title":"Work through the example","walkthrough":"The new reader accepts the old name field and prefers the additive display_name field when present. This is a migration model, not a universal rule to accept arbitrary input: strict external API validation and backward-compatible internal event readers can require different policies. Presence and an empty string may need a pointer or explicit optional type."},{"body":"A rename performed as drop-old/add-new in one release breaks old binaries during rollout and rollback. Avoid dual writes without a stated source of truth and reconciliation policy. Database index creation and long backfills also need operational budgets. Test old writer/new reader, new writer/old reader, rollback and replay of retained events before declaring the migration complete.","title":"Production decisions"},{"body":"An old worker may run for another hour. When may the old schema field be removed? After compatible readers are deployed, data is migrated and evidence shows old consumers no longer require it; rollback and event replay must still work. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Use expand–migrate–contract changes while old and new Go processes coexist. After compatible readers are deployed, data is migrated and evidence shows old consumers no longer require it; rollback and event replay must still work.","title":"Evolve APIs, events and schemas across mixed deployments","unitID":"system-design","wrongAnswers":["Rename and drop everything in one rollout","Assume Go compilation tests old clients"]},{"conceptTag":"systems.tenant-isolation","designGuide":{"cautions":["A helper named GetByID can bypass isolation even if the list endpoint filters correctly.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Verify principal","Authorize tenant + resource","Scope data and cache","Test crossing attempts"],"ratings":[],"strengths":["Carry a verified tenant identity into storage predicates, cache keys and background jobs.","Makes the owner and the failure boundary explicit."]},"hint":"The composite key demonstrates why order ID alone is insufficient when IDs are only unique within a tenant.","id":"systems.tenant-isolation","introduction":"A request can be authenticated and still read another tenant’s object. Authentication proves a principal; authorization decides whether that principal may perform this operation on this resource. Tenant isolation fails when one endpoint is careful but a cache key, bulk export or queued job forgets the same boundary. Treat tenant identity as part of the operation contract.","nuance":"No. The verified tenant scope must participate in lookup and authorization, including the cache key, storage predicate and job context.","objective":"Carry a verified tenant identity into storage predicates, cache keys and background jobs.","question":"Which invariant must cover database queries and cache lookups in a multi-tenant service?","references":["https://pkg.go.dev/context","https://www.postgresql.org/docs/current/ddl-rowsecurity.html"],"reviewAnswer":"Verified identity + scoped access on every path","reviewPrompt":"Tenant-scoped resource","sections":[{"body":"A request can be authenticated and still read another tenant’s object. Authentication proves a principal; authorization decides whether that principal may perform this operation on this resource. Tenant isolation fails when one endpoint is careful but a cache key, bulk export or queued job forgets the same boundary. Treat tenant identity as part of the operation contract.","title":"The contract and the failure"},{"body":"Use tenant and resource together in query predicates and uniqueness constraints. A background job records a verified tenant scope and rechecks the relevant permission where policy requires it. Include tenant scope in cache and idempotency keys, pagination cursors and object-storage paths. Consider database row-level security as defense in depth, with explicit connection/session reset rules.","code":"package main\n\nimport \"fmt\"\n\ntype Key struct{ Tenant, Order string }\n\nfunc main() {\n\tcache := map[Key]string{}\n\tcache[Key{\"tenant-a\", \"42\"}] = \"Ada's order\"\n\tcache[Key{\"tenant-b\", \"42\"}] = \"Grace's order\"\n\tfmt.Println(cache[Key{\"tenant-a\", \"42\"}])\n\tfmt.Println(cache[Key{\"tenant-b\", \"42\"}])\n}","language":"go","title":"Work through the example","walkthrough":"The composite key demonstrates why order ID alone is insufficient when IDs are only unique within a tenant. It is not an authorization system. Production code must derive the tenant from a verified principal and membership check, not accept an arbitrary X-Tenant header as authority."},{"body":"A helper named GetByID can bypass isolation even if the list endpoint filters correctly. Shared cache entries and metrics labels can leak data or create unbounded cardinality. Test two tenants with the same resource ID, guessed IDs, stale permissions, bulk operations and queued work. A context value transports identity; it does not validate the identity or replace an explicit authorization decision.","title":"Production decisions"},{"body":"Two tenants use order ID 42. Is a cache key containing only 42 safe? No. The verified tenant scope must participate in lookup and authorization, including the cache key, storage predicate and job context. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Carry a verified tenant identity into storage predicates, cache keys and background jobs. No. The verified tenant scope must participate in lookup and authorization, including the cache key, storage predicate and job context.","title":"Tenant isolation belongs in every access path","unitID":"system-design","wrongAnswers":["Trust a client-supplied tenant header","Scope list queries but not cache entries"]},{"conceptTag":"systems.observability","designGuide":{"cautions":["User IDs, transaction hashes and raw URLs as metric labels create unbounded time series.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Define objective","Measure boundary","Trace dependencies","Act on evidence"],"ratings":[],"strengths":["Connect structured logs, bounded metrics and traces to an explicit service objective.","Makes the owner and the failure boundary explicit."]},"hint":"The event has a fixed message and named fields, so a reader can search by operation and reason rather than parse prose.","id":"systems.observability","introduction":"A service can emit millions of log lines while providing no evidence about a failed business operation. Start with a question: is the checkout successful within its time budget, and where is the budget spent? Logs explain individual events, metrics describe distributions and rates, and traces connect sampled work across boundaries. They should share stable operation semantics without sharing every field.","nuance":"Keep high-cardinality identifiers in appropriately protected logs or traces; metrics use a bounded set of operation and outcome labels.","objective":"Connect structured logs, bounded metrics and traces to an explicit service objective.","question":"Where should a unique transaction hash appear: every metric label or selected logs/traces?","references":["https://pkg.go.dev/log/slog","https://opentelemetry.io/docs/languages/go/"],"reviewAnswer":"Bounded metric labels, IDs in logs or traces","reviewPrompt":"Telemetry cardinality","sections":[{"body":"A service can emit millions of log lines while providing no evidence about a failed business operation. Start with a question: is the checkout successful within its time budget, and where is the budget spent? Logs explain individual events, metrics describe distributions and rates, and traces connect sampled work across boundaries. They should share stable operation semantics without sharing every field.","title":"The contract and the failure"},{"body":"Define latency and error SLIs at the user-visible boundary. Measure dependency waiting separately from execution, and include retries in the end-to-end budget. Use bounded labels such as operation and outcome. Put trace/request identifiers in logs or exemplars. With OpenTelemetry, propagate context, end spans, record errors appropriately and flush exporters during bounded shutdown.","code":"package main\n\nimport (\n\t\"context\"\n\t\"log/slog\"\n\t\"os\"\n)\n\nfunc main() {\n\tlogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))\n\tctx := context.Background()\n\tlogger.InfoContext(ctx, \"order rejected\", \"operation\", \"place_order\", \"reason\", \"insufficient_stock\", \"request_id\", \"req-example\")\n}","language":"go","title":"Work through the example","walkthrough":"The event has a fixed message and named fields, so a reader can search by operation and reason rather than parse prose. request_id is a log field, not a metric dimension. slog does not automatically create a distributed trace; tracing requires explicit instrumentation and propagation configured in the native service."},{"body":"User IDs, transaction hashes and raw URLs as metric labels create unbounded time series. Logging tokens, keys or entire request bodies leaks secrets. A healthy average hides tail latency and errors hidden by retries. Test redaction, cancellation and exporter failure; telemetry failure must not accidentally become an unbounded request queue. Pick alerts that correspond to an actionable service objective.","title":"Production decisions"},{"body":"Where should a unique transaction hash appear: every metric label or selected logs/traces? Keep high-cardinality identifiers in appropriately protected logs or traces; metrics use a bounded set of operation and outcome labels. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Connect structured logs, bounded metrics and traces to an explicit service objective. Keep high-cardinality identifiers in appropriately protected logs or traces; metrics use a bounded set of operation and outcome labels.","title":"Observe a Go use case without drowning in cardinality","unitID":"system-design","wrongAnswers":["Every request ID becomes a metric label","A log line automatically creates a trace"]},{"conceptTag":"clean-production.composition","designGuide":{"cautions":["A dependency-injection framework cannot infer the correct business lifetime.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"clean-code-production","flow":["Validate config","Construct dependencies","Serve borrowed clients","Drain then close"],"ratings":[],"strengths":["Construct dependencies once and make their ownership and shutdown order explicit.","Makes the owner and the failure boundary explicit."]},"hint":"main owns the client and schedules its cleanup exactly once.","id":"clean-production.composition","introduction":"Dependency injection in Go is usually ordinary constructors and parameters. The important question is not which container library to use but who creates a shared client, who is allowed to close it and how partial startup is cleaned up. Keep wiring near main so a handler cannot silently allocate a new database pool or depend on a hidden global singleton.","nuance":"No. The composition root owns the shared client; requests borrow it and close only request-scoped resources such as rows or bodies.","objective":"Construct dependencies once and make their ownership and shutdown order explicit.","question":"Who should own construction and shutdown of shared service dependencies?","references":["https://go.dev/doc/effective_go","https://pkg.go.dev/io#Closer","https://pkg.go.dev/database/sql#DB"],"reviewAnswer":"Wiring owns startup, lifetimes and shutdown","reviewPrompt":"Composition root","sections":[{"body":"Dependency injection in Go is usually ordinary constructors and parameters. The important question is not which container library to use but who creates a shared client, who is allowed to close it and how partial startup is cleaned up. Keep wiring near main so a handler cannot silently allocate a new database pool or depend on a hidden global singleton.","title":"The contract and the failure"},{"body":"Accept concrete values until a boundary genuinely needs an interface. Validate configuration before serving traffic. Constructors return errors for required setup and document whether they take ownership. Separate startup, serving and shutdown contexts. Stop accepting work, drain owners and only then close shared dependencies; closing the pool first makes graceful shutdown generate avoidable failures.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n)\n\ntype Client struct{ name string }\n\nfunc (c *Client) Close() error { fmt.Println(\"close\", c.name); return nil }\n\ntype Service struct{ client *Client }\n\nfunc main() {\n\tclient := &Client{name: \"shared-store\"}\n\tvar closer io.Closer = client\n\tdefer closer.Close()\n\tservice := Service{client: client}\n\tfmt.Println(service.client.name)\n}","language":"go","title":"Work through the example","walkthrough":"main owns the client and schedules its cleanup exactly once. Service borrows the client and does not close it after each request. The example omits a real database so its lifetime is visible without a network. In production, unwind resources created before any later constructor fails and report shutdown errors according to their significance."},{"body":"A dependency-injection framework cannot infer the correct business lifetime. A request-scoped service may borrow a process-scoped client, but a process-scoped service must not retain a request context. Test partial startup failure, duplicate Close, expired request contexts and shutdown ordering. Avoid packages that read environment variables or open connections as import-time side effects.","title":"Production decisions"},{"body":"A service receives a shared database client. Should each request close it? No. The composition root owns the shared client; requests borrow it and close only request-scoped resources such as rows or bodies. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Construct dependencies once and make their ownership and shutdown order explicit. No. The composition root owns the shared client; requests borrow it and close only request-scoped resources such as rows or bodies.","title":"A composition root makes lifetime and cleanup visible","unitID":"clean-code-production","wrongAnswers":["Each handler creates and closes its own pool","A global client removes ownership questions"]},{"conceptTag":"clean-production.context-contracts","designGuide":{"cautions":["Storing a request context in a long-lived struct can retain request data and cancel unrelated work.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"clean-code-production","flow":["Request context","Bounded dependency","Cancellation signal","Owner joins or queues"],"ratings":[],"strengths":["Propagate request cancellation while giving detached work an explicit owner and deadline.","Makes the owner and the failure boundary explicit."]},"hint":"Err identifies cancellation broadly; Cause retains the chosen explanation.","id":"clean-production.context-contracts","introduction":"Passing context.Context as the first parameter lets cancellation and deadlines cross a call boundary. It does not force the callee to stop, and it does not prove that a goroutine has exited. Context values are for request-scoped metadata that must cross API boundaries, not an alternative constructor or a hidden transport for required service dependencies.","nuance":"No. It removes cancellation and deadline propagation; detached work needs a separately owned context, budget and completion or recovery policy.","objective":"Propagate request cancellation while giving detached work an explicit owner and deadline.","question":"Which contract should govern cancellation and work detached from a request?","references":["https://pkg.go.dev/context#WithoutCancel","https://pkg.go.dev/context#WithCancelCause"],"reviewAnswer":"Propagate stop; join or durably own detached work","reviewPrompt":"Cancellation ownership","sections":[{"body":"Passing context.Context as the first parameter lets cancellation and deadlines cross a call boundary. It does not force the callee to stop, and it does not prove that a goroutine has exited. Context values are for request-scoped metadata that must cross API boundaries, not an alternative constructor or a hidden transport for required service dependencies.","title":"The contract and the failure"},{"body":"Pass the request context into storage and outgoing calls. Check cancellation at meaningful handoffs and stop producers as well as consumers. For must-complete work, prefer a durable job or an application-owned worker with an explicit shutdown budget. Keep tenant/principal values typed and verified; an arbitrary value in context does not establish authorization.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tctx, cancel := context.WithCancelCause(context.Background())\n\tcancel(errors.New(\"request no longer needed\"))\n\tfmt.Println(ctx.Err())          // context canceled\n\tfmt.Println(context.Cause(ctx)) // request no longer needed\n\tdetached := context.WithoutCancel(ctx)\n\tfmt.Println(detached.Err(), detached.Done() == nil) // <nil> true\n}","language":"go","title":"Work through the example","walkthrough":"Err identifies cancellation broadly; Cause retains the chosen explanation. WithoutCancel removes the parent cancellation, deadline and Done signal, so it must not be used as a convenient way to make an unowned goroutine live forever. A background owner must supply its own bounded context and join or durably queue the work."},{"body":"Storing a request context in a long-lived struct can retain request data and cancel unrelated work. Replacing every context with Background hides client cancellation. Calling cancel alone does not join a worker. Test cancellation while waiting, during an operation and after the caller stops reading results. Explain which side owns the result channel and how both sides exit.","title":"Production decisions"},{"body":"Does context.WithoutCancel preserve the request deadline? No. It removes cancellation and deadline propagation; detached work needs a separately owned context, budget and completion or recovery policy. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Propagate request cancellation while giving detached work an explicit owner and deadline. No. It removes cancellation and deadline propagation; detached work needs a separately owned context, budget and completion or recovery policy.","title":"Context is a cancellation contract, not a bag of dependencies","unitID":"clean-code-production","wrongAnswers":["Cancel proves every goroutine exited","WithoutCancel supplies a new timeout"]},{"conceptTag":"clean-production.package-apis","designGuide":{"cautions":["Creating an interface for every struct increases maintenance without adding a boundary.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"clean-code-production","flow":["Name capability","Keep implementation private","Test public contract","Integrate real adapter"],"ratings":[],"strengths":["Use narrow consumer contracts and tests that make accidental coupling visible.","Makes the owner and the failure boundary explicit."]},"hint":"The reader contract is declared near its consumer and contains one capability.","id":"clean-production.package-apis","introduction":"A repository with packages named controllers, managers and utils can still have no useful boundaries. Ask which behavior changes together and which caller is allowed to depend on it. Go import cycles are prohibited, but a cycle-free graph can still expose every storage struct and force unrelated features to change together. Test the public behavior of a capability, not its current arrangement of private helper calls.","nuance":"Prefer the narrow capability the consumer needs; keep driver and transaction details in adapters and verify those with real integration tests.","objective":"Use narrow consumer contracts and tests that make accidental coupling visible.","question":"How should a consumer define its interface when it only needs to read one order?","references":["https://go.dev/doc/effective_go#interfaces","https://go.dev/doc/modules/layout"],"reviewAnswer":"The caller names the capability it needs","reviewPrompt":"Consumer contract","sections":[{"body":"A repository with packages named controllers, managers and utils can still have no useful boundaries. Ask which behavior changes together and which caller is allowed to depend on it. Go import cycles are prohibited, but a cycle-free graph can still expose every storage struct and force unrelated features to change together. Test the public behavior of a capability, not its current arrangement of private helper calls.","title":"The contract and the failure"},{"body":"Return domain values rather than leaking driver-specific result types across every layer. Export the smallest useful API, document error and ownership contracts, and use external package tests where appropriate to exercise what users can actually call. Use integration tests for serialization, SQL and network semantics that a fake cannot reproduce.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n)\n\ntype Order struct{ ID string }\n\n// The consumer needs this capability, not every method of a database client.\ntype OrderReader interface {\n\tFind(context.Context, string) (Order, error)\n}\ntype Memory struct{ orders map[string]Order }\n\nfunc (m Memory) Find(_ context.Context, id string) (Order, error) {\n\tvalue, ok := m.orders[id]\n\tif !ok {\n\t\treturn Order{}, fmt.Errorf(\"order absent\")\n\t}\n\treturn value, nil\n}\nfunc describe(ctx context.Context, reader OrderReader) {\n\to, err := reader.Find(ctx, \"7\")\n\tfmt.Println(o.ID, err)\n}\nfunc main() { describe(context.Background(), Memory{map[string]Order{\"7\": {ID: \"7\"}}}) }","language":"go","title":"Work through the example","walkthrough":"The reader contract is declared near its consumer and contains one capability. The adapter satisfies it implicitly. In a real module, put private implementation under internal where the import rules fit the intended boundary. The tiny memory implementation is a test seam, not proof that a database adapter follows the same transaction and cancellation behavior."},{"body":"Creating an interface for every struct increases maintenance without adding a boundary. A mock that asserts a private call order can reject a harmless refactor and miss a broken transaction. Avoid a shared models package that makes every subsystem depend on every field. Test contract cases against both a fake and the real adapter when substitutability matters.","title":"Production decisions"},{"body":"Should a consumer depend on a full database client when it only reads one order? Prefer the narrow capability the consumer needs; keep driver and transaction details in adapters and verify those with real integration tests. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Use narrow consumer contracts and tests that make accidental coupling visible. Prefer the narrow capability the consumer needs; keep driver and transaction details in adapters and verify those with real integration tests.","title":"Package APIs should reveal their change boundary","unitID":"clean-code-production","wrongAnswers":["Every implementation needs a large interface","A mock proves database isolation semantics"]},{"conceptTag":"clean-production.time-money","designGuide":{"cautions":["Do not guess units from a JSON number or infer token decimals from a symbol.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"clean-code-production","flow":["Parse with units","Validate range/presence","Keep exact representation","Convert at boundary"],"ratings":[],"strengths":["Separate durations, instants and exact amounts instead of passing ambiguous numbers.","Makes the owner and the failure boundary explicit."]},"hint":"The duration is explicitly milliseconds, the amount is cents, and the large token amount is parsed without a floating-point round trip.","id":"clean-production.time-money","introduction":"An int64 does not tell the next engineer whether it represents milliseconds, Unix seconds, cents or token base units. A float64 cannot represent every decimal amount exactly. At API boundaries, define units, range, rounding and whether a missing field differs from zero. Inside the program, use types and constructors that make those contracts difficult to confuse.","nuance":"No. Parse exact integer base units or validated decimal text directly, and make scaling, range and rounding explicit.","objective":"Separate durations, instants and exact amounts instead of passing ambiguous numbers.","question":"What contract should protect a token amount with 18 decimal places during serialization and conversion?","references":["https://pkg.go.dev/math/big#Int","https://pkg.go.dev/time#Time"],"reviewAnswer":"Explicit units, exact values, deliberate conversion","reviewPrompt":"Exact amounts and time","sections":[{"body":"An int64 does not tell the next engineer whether it represents milliseconds, Unix seconds, cents or token base units. A float64 cannot represent every decimal amount exactly. At API boundaries, define units, range, rounding and whether a missing field differs from zero. Inside the program, use types and constructors that make those contracts difficult to confuse.","title":"The contract and the failure"},{"body":"Use time.Duration for elapsed budgets and time.Time for instants. Calendar schedules need a named location and explicit daylight-saving behavior. Go time values may contain a monotonic component for local elapsed measurements; serialization does not preserve that local clock reading. Use integer base units or a reviewed decimal package for money and validate scaling at the input boundary.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n\t\"time\"\n)\n\ntype Cents int64\n\nfunc main() {\n\ttimeout := 250 * time.Millisecond\n\tprice := Cents(199)\n\traw, ok := new(big.Int).SetString(\"1000000000000000001\", 10)\n\tif !ok {\n\t\tpanic(\"invalid integer\")\n\t}\n\tcopied := new(big.Int).Set(raw)\n\tcopied.Add(copied, big.NewInt(1))\n\tfmt.Println(timeout, price, raw.String(), copied.String())\n}","language":"go","title":"Work through the example","walkthrough":"The duration is explicitly milliseconds, the amount is cents, and the large token amount is parsed without a floating-point round trip. big.Int operations mutate their receiver, so Set makes the independent copy before adding. The example demonstrates representation only; currency conversion, decimal formatting and overflow policy still need explicit rules."},{"body":"Do not guess units from a JSON number or infer token decimals from a symbol. A pointer or optional type may distinguish omitted from zero. Check overflow before multiplication in fixed-width money types. Test rounding boundaries, negative amounts, maximum values, different decimal scales, a daylight-saving transition and serialization/restart of timestamps.","title":"Production decisions"},{"body":"Can a token amount with 18 decimals safely travel through float64 before big.Int? No. Parse exact integer base units or validated decimal text directly, and make scaling, range and rounding explicit. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Separate durations, instants and exact amounts instead of passing ambiguous numbers. No. Parse exact integer base units or validated decimal text directly, and make scaling, range and rounding explicit.","title":"Time and money need units and presence in their types","unitID":"clean-code-production","wrongAnswers":["float64 stores every token amount exactly","A serialized timestamp retains a local monotonic clock"]},{"conceptTag":"concurrency.atomic-snapshots","designGuide":{"cautions":["Publishing a pointer and then changing its map races with readers.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"concurrency","flow":["Build independent state","Publish one pointer","Read one snapshot","Never mutate published graph"],"ratings":[],"strengths":["Publish one consistent snapshot and preserve ownership of its reachable maps and slices.","Makes the owner and the failure boundary explicit."]},"hint":"The map is copied before the pointer is stored.","id":"concurrency.atomic-snapshots","introduction":"An atomic load or store synchronizes an operation on the atomic value. It does not recursively make the object graph immutable or protect a later map mutation. A useful read-mostly pattern builds a complete independent configuration, publishes one pointer and lets readers hold that immutable snapshot. All fields that must agree belong to the same published value.","nuance":"No. Atomic publication protects the pointer protocol, not later mutations of reachable state; publish independent immutable data or use a lock.","objective":"Publish one consistent snapshot and preserve ownership of its reachable maps and slices.","question":"After storing *Config atomically, may a writer mutate its map while readers use it?","references":["https://pkg.go.dev/sync/atomic#Pointer","https://go.dev/ref/mem","https://pkg.go.dev/sync#Map"],"reviewAnswer":"Publish once; keep reachable state immutable","reviewPrompt":"Atomic snapshot publication","sections":[{"body":"An atomic load or store synchronizes an operation on the atomic value. It does not recursively make the object graph immutable or protect a later map mutation. A useful read-mostly pattern builds a complete independent configuration, publishes one pointer and lets readers hold that immutable snapshot. All fields that must agree belong to the same published value.","title":"The contract and the failure"},{"body":"Choose a mutex when operations update related state together; choose an atomic primitive only for a precisely defined protocol. Atomic types and mutexes must not be copied after first use. If a snapshot contains slices, pointers or nested maps, define deep-enough copying and lifetime rules. Compare this with sync.Map, whose per-operation contracts do not provide a transaction across arbitrary keys.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n)\n\ntype Config struct{ limits map[string]int }\n\nfunc publish(dst *atomic.Pointer[Config], src map[string]int) {\n\tcopied := make(map[string]int, len(src))\n\tfor k, v := range src {\n\t\tcopied[k] = v\n\t}\n\tdst.Store(&Config{limits: copied})\n}\nfunc main() {\n\tvar current atomic.Pointer[Config]\n\tinput := map[string]int{\"workers\": 4}\n\tpublish(&current, input)\n\tinput[\"workers\"] = 99\n\tsnapshot := current.Load()\n\tfmt.Println(snapshot.limits[\"workers\"]) // 4\n}","language":"go","title":"Work through the example","walkthrough":"The map is copied before the pointer is stored. Changing the caller’s input afterward does not mutate the published configuration. Readers load one pointer and keep that snapshot, rather than loading separate fields at different times. A production API should avoid exposing a mutable map from the snapshot to callers."},{"body":"Publishing a pointer and then changing its map races with readers. Two independent atomic fields do not automatically form a consistent pair. Race detection finds executed data races, not every logical ordering error. Test concurrent publication/read behavior and business invariants with native go test -race; the app sandbox does not supply a native race detector.","title":"Production decisions"},{"body":"After storing *Config atomically, may a writer mutate its map while readers use it? No. Atomic publication protects the pointer protocol, not later mutations of reachable state; publish independent immutable data or use a lock. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Publish one consistent snapshot and preserve ownership of its reachable maps and slices. No. Atomic publication protects the pointer protocol, not later mutations of reachable state; publish independent immutable data or use a lock.","title":"Atomic publication is safe only when the published snapshot stays immutable","unitID":"concurrency","wrongAnswers":["Atomic pointers make every pointed-to map safe","Two independent atomics form one transaction"]},{"conceptTag":"concurrency.lock-ownership","designGuide":{"cautions":["Do not copy mutex-bearing values after use, embed them into casually copied API results or return internal maps after unlocking.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"concurrency","flow":["Define invariant","Keep one lock owner","Copy returned data","Test races and business outcomes"],"ratings":[],"strengths":["Choose synchronization around related state and return snapshots rather than copied lock owners.","Makes the owner and the failure boundary explicit."]},"hint":"Both methods use pointer receivers so calls share the lock owner.","id":"concurrency.lock-ownership","introduction":"The presence of a mutex in a struct does not prove that every operation locks the same mutex. A value receiver or assignment can copy the lock while retaining a reference to the same map. Likewise, sync.Map protects its own operations but cannot infer an invariant spanning several keys. Define the state that must change together and keep one synchronization owner for that state.","nuance":"The lock is copied while the map storage remains shared. Use a stable lock owner and pointer receivers; test both races and the compound invariant.","objective":"Choose synchronization around related state and return snapshots rather than copied lock owners.","question":"Which rule should govern a shared map and the mutex protecting its multi-step invariant?","references":["https://pkg.go.dev/sync#Mutex","https://pkg.go.dev/sync#Map","https://go.dev/cmd/vet/"],"reviewAnswer":"One invariant, one shared synchronization protocol","reviewPrompt":"Lock ownership","sections":[{"body":"The presence of a mutex in a struct does not prove that every operation locks the same mutex. A value receiver or assignment can copy the lock while retaining a reference to the same map. Likewise, sync.Map protects its own operations but cannot infer an invariant spanning several keys. Define the state that must change together and keep one synchronization owner for that state.","title":"The contract and the failure"},{"body":"Use RWMutex when measured read contention justifies it; long-held read locks can still delay writers. A mutex protects the whole declared invariant only if every access participates in the same protocol. sync.Map is suited to documented use patterns such as mostly stable keys or disjoint key ownership, not an automatic replacement for a typed map with multi-step business operations.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype Cache struct {\n\tmu     sync.Mutex\n\tvalues map[string]int\n}\n\nfunc (c *Cache) Put(k string, v int) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tif c.values == nil {\n\t\tc.values = map[string]int{}\n\t}\n\tc.values[k] = v\n}\nfunc (c *Cache) Snapshot() map[string]int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tout := make(map[string]int, len(c.values))\n\tfor k, v := range c.values {\n\t\tout[k] = v\n\t}\n\treturn out\n}\nfunc main() {\n\tvar c Cache\n\tc.Put(\"a\", 1)\n\tcopy := c.Snapshot()\n\tcopy[\"a\"] = 99\n\tfmt.Println(c.Snapshot()[\"a\"])\n}","language":"go","title":"Work through the example","walkthrough":"Both methods use pointer receivers so calls share the lock owner. Snapshot returns independent map storage rather than returning Cache by value or exposing the internal map. This example uses simple scalar values; references inside values would need their own ownership or deeper-copy contract."},{"body":"Do not copy mutex-bearing values after use, embed them into casually copied API results or return internal maps after unlocking. go vet copylocks helps identify copied locks; native race tests exercise actual access paths. A race-free get-then-put can still duplicate a business action. Test lost updates, snapshots, simultaneous misses and compound invariants separately from the absence of a data-race report.","title":"Production decisions"},{"body":"A struct with a mutex and a map uses a value receiver. What can go wrong? The lock is copied while the map storage remains shared. Use a stable lock owner and pointer receivers; test both races and the compound invariant. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Choose synchronization around related state and return snapshots rather than copied lock owners. The lock is copied while the map storage remains shared. Use a stable lock owner and pointer receivers; test both races and the compound invariant.","title":"Mutex, RWMutex and sync.Map: protect the invariant and do not copy the lock","unitID":"concurrency","wrongAnswers":["Copy the mutex to get independent map safety","sync.Map makes arbitrary multi-key workflows atomic"]},{"conceptTag":"stdlib.timer-contracts","designGuide":{"cautions":["Repeated time.After in a hot loop allocates timers and is not a substitute for a clear lifecycle.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"stdlib","flow":["Choose documented semantics","Keep one timer owner","Select ready events","Check state before effect"],"ratings":[],"strengths":["Explain Stop/Reset behavior, timer ownership and why select is not a priority statement.","Makes the owner and the failure boundary explicit."]},"hint":"One goroutine creates, resets and receives the timer.","id":"stdlib.timer-contracts","introduction":"Timers have both an API contract and version-dependent implementation behavior. Modern Go timer channels avoid the old buffered stale-value behavior under the documented module/runtime conditions, but this does not let several goroutines reset, receive and decide business state without a protocol. Treat a timer as one owner’s scheduling tool and separately define which events may commit work.","nuance":"No. Ready cases have no source-order priority; define ownership and commit checks explicitly rather than depending on select order.","objective":"Explain Stop/Reset behavior, timer ownership and why select is not a priority statement.","question":"If ctx.Done is the first select case and another case is ready, does cancellation always win?","references":["https://pkg.go.dev/time#Timer.Stop","https://pkg.go.dev/time#Timer.Reset","https://go.dev/wiki/Go123Timer"],"reviewAnswer":"One timer owner; ready select cases have no priority","reviewPrompt":"Timer and select ownership","sections":[{"body":"Timers have both an API contract and version-dependent implementation behavior. Modern Go timer channels avoid the old buffered stale-value behavior under the documented module/runtime conditions, but this does not let several goroutines reset, receive and decide business state without a protocol. Treat a timer as one owner’s scheduling tool and separately define which events may commit work.","title":"The contract and the failure"},{"body":"For Go 1.23-and-later timer-channel semantics, inspect the module’s go directive and any asynctimerchan compatibility setting when diagnosing old patterns. Do not use len(timer.C) to synchronize. Stop/Reset documentation distinguishes modern guarantees from older drain patterns. A select with several ready cases chooses among them; listing ctx.Done first does not grant cancellation priority.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\ttimer := time.NewTimer(time.Hour)\n\tdefer timer.Stop()\n\ttimer.Reset(0)\n\t<-timer.C\n\tfmt.Println(\"one owner received the reset timer\")\n}","language":"go","title":"Work through the example","walkthrough":"One goroutine creates, resets and receives the timer. No second receiver can consume its event unexpectedly. The example does not infer fairness or a global ordering against cancellation from a timer firing. It is compatible with the modern timer contract used by the course; review the time package documentation when maintaining older modules or runtime compatibility settings."},{"body":"Repeated time.After in a hot loop allocates timers and is not a substitute for a clear lifecycle. Stopping a timer does not close its channel or prove a worker exited. If cancellation must prevent a side effect, recheck the operation state under the same synchronization that commits the effect. Test ready timer plus cancellation, reset ownership and shutdown without relying on lucky sleeps.","title":"Production decisions"},{"body":"If ctx.Done is the first select case and another case is ready, does cancellation always win? No. Ready cases have no source-order priority; define ownership and commit checks explicitly rather than depending on select order. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Explain Stop/Reset behavior, timer ownership and why select is not a priority statement. No. Ready cases have no source-order priority; define ownership and commit checks explicitly rather than depending on select order.","title":"Timers and cancellation: versioned semantics still need a single owner","unitID":"stdlib","wrongAnswers":["First select case always wins","Stopping a timer closes its channel"]},{"conceptTag":"stdlib.http-client-budgets","designGuide":{"cautions":["Creating a new transport per request loses useful pooling and may waste sockets.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"stdlib","flow":["Reuse owned client","Bound request lifetime","Check status + body limit","Close and classify outcome"],"ratings":[],"strengths":["Own the client lifetime, close bodies and classify HTTP status separately from transport failure.","Makes the owner and the failure boundary explicit."]},"hint":"The body is limited to the allowed bytes plus one detection byte, so a truncated success cannot be mistaken for a complete valid response.","id":"stdlib.http-client-budgets","introduction":"A successful Client.Do means an HTTP response was received, not that the application operation succeeded. An error page can still be a valid response, and a server can keep streaming bytes after the headers arrive. Reuse the client and transport, pass an operation context and bound both elapsed time and bytes consumed. Closing the body is necessary even when status handling returns early.","nuance":"No. Check status, bound time and response bytes, validate parsing and always close the body; retry semantics depend on the operation.","objective":"Own the client lifetime, close bodies and classify HTTP status separately from transport failure.","question":"Which policy should govern an HTTP client used by a busy service?","references":["https://pkg.go.dev/net/http#Client","https://pkg.go.dev/io#LimitReader","https://pkg.go.dev/net/http/httptest"],"reviewAnswer":"Reuse client; bound time, bytes and retry semantics","reviewPrompt":"Outgoing HTTP budget","sections":[{"body":"A successful Client.Do means an HTTP response was received, not that the application operation succeeded. An error page can still be a valid response, and a server can keep streaming bytes after the headers arrive. Reuse the client and transport, pass an operation context and bound both elapsed time and bytes consumed. Closing the body is necessary even when status handling returns early.","title":"The contract and the failure"},{"body":"Validate the configured positive byte limit and keep its arithmetic within range in a real API. Check status before parsing a success DTO, classify retryable failures and make unsafe writes retry only under an idempotency policy. Bound decompressed response bytes too. Reusing a transport enables connection pooling; reading to EOF can help reuse, but do not drain an untrusted infinite body merely to save a connection.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n)\n\nfunc get(ctx context.Context, c *http.Client, url string, limit int64) ([]byte, error) {\n\treq, err := http.NewRequestWithContext(ctx, \"GET\", url, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := c.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, fmt.Errorf(\"upstream status %d\", resp.StatusCode)\n\t}\n\tbody, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif int64(len(body)) > limit {\n\t\treturn nil, fmt.Errorf(\"response exceeds %d bytes\", limit)\n\t}\n\treturn body, nil\n}\nfunc main() {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(\"four\")) }))\n\tdefer server.Close()\n\tclient := &http.Client{Timeout: 2 * time.Second}\n\t_, err := get(context.Background(), client, server.URL, 3)\n\tfmt.Println(err)\n}","language":"go","title":"Work through the example","walkthrough":"The body is limited to the allowed bytes plus one detection byte, so a truncated success cannot be mistaken for a complete valid response. Client.Timeout covers the overall request including body reading; the context can impose an earlier bound. The sample uses only a local test server and returns the explicit oversize error."},{"body":"Creating a new transport per request loses useful pooling and may waste sockets. Ignoring Close or using an unbounded ReadAll can exhaust memory. A timeout after sending a write leaves an unknown business outcome, even if no response body was received. Test slow headers, slow body, oversize decompressed data, non-2xx responses, redirects and cancellation in your native service.","title":"Production decisions"},{"body":"Does a nil error from http.Client.Do guarantee HTTP success and a small complete body? No. Check status, bound time and response bytes, validate parsing and always close the body; retry semantics depend on the operation. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Own the client lifetime, close bodies and classify HTTP status separately from transport failure. No. Check status, bound time and response bytes, validate parsing and always close the body; retry semantics depend on the operation.","title":"Outgoing HTTP: reuse the client and bound the response, not just the dial","unitID":"stdlib","wrongAnswers":["Do returns an error for every HTTP 500","Close alone proves a response was fully read"]},{"conceptTag":"systems.rpc-contracts","designGuide":{"cautions":["Do not reuse removed protobuf field numbers; reserve them and keep old message fixtures.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Version wire contract","Verify identity + budget","Bound stream ownership","Map outcomes + resume"],"ratings":[],"strengths":["Define deadlines, stream ownership, status mapping and compatible message evolution.","Makes the owner and the failure boundary explicit."]},"hint":"The cancelled context maps to the protocol’s cancellation status.","id":"systems.rpc-contracts","introduction":"Generated Go stubs remove repetitive transport code, not the need to design a distributed operation. A gRPC method can block, partially stream data, be retried or outlive its caller unless the application defines its lifetime. Treat protobuf fields as a versioned wire contract and the RPC method as a budgeted operation with explicit authorization and failure semantics.","nuance":"No. Define partial-result, durable-effect and resume/idempotency semantics; deadlines and generated types do not provide atomic rollback.","objective":"Define deadlines, stream ownership, status mapping and compatible message evolution.","question":"Which responsibilities remain with an application even when its RPC types are generated?","references":["https://grpc.io/docs/guides/deadlines/","https://protobuf.dev/programming-guides/proto3/","https://pkg.go.dev/google.golang.org/grpc/status"],"reviewAnswer":"Generated types still need budgets and replay rules","reviewPrompt":"RPC operational contract","sections":[{"body":"Generated Go stubs remove repetitive transport code, not the need to design a distributed operation. A gRPC method can block, partially stream data, be retried or outlive its caller unless the application defines its lifetime. Treat protobuf fields as a versioned wire contract and the RPC method as a budgeted operation with explicit authorization and failure semantics.","title":"The contract and the failure"},{"body":"Set or propagate deadlines because an RPC has no useful universal business timeout. Bound stream queues, use backpressure and make one goroutine own each send/receive direction according to the API contract. Verify metadata-based identity at the server rather than treating all metadata as trusted. Pin protoc and its Go plugins so generated code can be reproduced.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc classify(ctx context.Context) error {\n\tif err := ctx.Err(); err != nil {\n\t\treturn status.FromContextError(err).Err()\n\t}\n\treturn nil\n}\nfunc main() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\tcancel()\n\terr := classify(ctx)\n\tfmt.Println(status.Code(err) == codes.Canceled) // true, not DeadlineExceeded\n}","language":"go","title":"Work through the example","walkthrough":"The cancelled context maps to the protocol’s cancellation status. It is not rewritten as a successful empty result or confused with expiration of a deadline. In a real handler, domain errors need a deliberate status mapping that does not reveal internal credentials or SQL text; the client separately decides whether a retry is semantically safe."},{"body":"Do not reuse removed protobuf field numbers; reserve them and keep old message fixtures. A cancelled stream can already have produced durable effects or partial results. Retrying a stream or RPC requires an application identity and a resume/deduplication policy. Test old/new clients, missing deadlines, a slow peer, mid-stream failure and shutdown. Native gRPC networking is taught here, not added to the iOS guest runtime.","title":"Production decisions"},{"body":"A streaming RPC was cancelled after several replies. Can its entire operation be assumed to have had no effects? No. Define partial-result, durable-effect and resume/idempotency semantics; deadlines and generated types do not provide atomic rollback. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Define deadlines, stream ownership, status mapping and compatible message evolution. No. Define partial-result, durable-effect and resume/idempotency semantics; deadlines and generated types do not provide atomic rollback.","title":"gRPC and Protobuf: generated methods still need an operational contract","unitID":"system-design","wrongAnswers":["Generated code provides a business deadline","Reusing a removed field number is always compatible"]},{"conceptTag":"systems.messaging-offsets","designGuide":{"cautions":["Committing offset 14 while record 12 is unfinished can lose that work after a crash.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Partition owns order","Bound concurrent work","Persist idempotent effects","Commit contiguous prefix"],"ratings":[],"strengths":["Separate message delivery, durable effects and partition-offset ownership.","Makes the owner and the failure boundary explicit."]},"hint":"Offsets 11 and 13 are complete, but the next safe offset remains 12.","id":"systems.messaging-offsets","introduction":"A broker can redeliver messages after a consumer crash or partition reassignment. Processing records concurrently makes offset handling more subtle: finishing a later record does not prove that earlier records are durable. Track completion per partition and advance only across the contiguous successful prefix. The business effect needs its own deduplication or transaction protocol.","nuance":"No. Commit only the next offset after the contiguous durable prefix; otherwise a restart can skip the unfinished record.","objective":"Separate message delivery, durable effects and partition-offset ownership.","question":"Records 11 and 13 finished but 12 did not. May the consumer commit a resume offset of 14?","references":["https://github.com/twmb/franz-go","https://kafka.apache.org/documentation/#semantics","https://go.dev/ref/mem"],"reviewAnswer":"Advance only across durable contiguous completions","reviewPrompt":"Partition offset commit","sections":[{"body":"A broker can redeliver messages after a consumer crash or partition reassignment. Processing records concurrently makes offset handling more subtle: finishing a later record does not prove that earlier records are durable. Track completion per partition and advance only across the contiguous successful prefix. The business effect needs its own deduplication or transaction protocol.","title":"The contract and the failure"},{"body":"Define the key used for partitioning, the scope of ordering and what counts as durable processing. Commit after the required effect, and retain a stable event identity for idempotent storage changes. Bound queued and in-flight records, observe lag and define a poison-record policy. Libraries such as franz-go provide Kafka protocol clients, not a transaction spanning an arbitrary database and external API.","code":"package main\n\nimport \"fmt\"\n\nfunc nextOffset(start int64, done map[int64]bool) int64 {\n\tfor done[start] {\n\t\tstart++\n\t}\n\treturn start\n}\nfunc main() {\n\tdone := map[int64]bool{11: true, 13: true}\n\tfmt.Println(nextOffset(11, done)) // 12: cannot skip unfinished 12\n\tdone[12] = true\n\tfmt.Println(nextOffset(11, done)) // 14: resume after the completed prefix\n}","language":"go","title":"Work through the example","walkthrough":"Offsets 11 and 13 are complete, but the next safe offset remains 12. Once 12 completes, the contiguous prefix ends before 14, so 14 is the next record to resume. This pure function models commit arithmetic; actual Go clients have specific commit, rebalance and transaction APIs that must be checked for the pinned version."},{"body":"Committing offset 14 while record 12 is unfinished can lose that work after a crash. Committing too late can cause duplicates, which is safer only when the effect is replay-safe. During rebalance, an old worker can finish after ownership moved; fence or reconcile its business effects and follow the client’s partition-revocation contract. Test out-of-order completion, duplicates, crash, rebalance and broker timeout.","title":"Production decisions"},{"body":"Records 11 and 13 finished but 12 did not. May the consumer commit a resume offset of 14? No. Commit only the next offset after the contiguous durable prefix; otherwise a restart can skip the unfinished record. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Separate message delivery, durable effects and partition-offset ownership. No. Commit only the next offset after the contiguous durable prefix; otherwise a restart can skip the unfinished record.","title":"Kafka-style consumers: commit only a contiguous completed prefix","unitID":"system-design","wrongAnswers":["Commit the largest completed offset immediately","A broker transaction makes every external API atomic"]},{"conceptTag":"systems.consistency-partitions","designGuide":{"cautions":["Do not claim that a system simply chooses any two of consistency, availability and partition tolerance.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"system-design","flow":["Define operation guarantee","Identify authoritative state","Handle lost coordination","Reconcile and fault-test"],"ratings":[],"strengths":["Choose per-operation consistency and failure behavior instead of treating CAP as a product rating.","Makes the owner and the failure boundary explicit."]},"hint":"Three acknowledgements meet a simple majority threshold for five configured replicas; two do not.","id":"systems.consistency-partitions","introduction":"A network partition can prevent replicas from coordinating. Whether a particular operation may proceed depends on the required consistency contract and the available authority, not on whether the service was written in Go or has a cache. Specify which reads may be stale, which writes require a leader or quorum, and what the caller sees when that requirement cannot be met.","nuance":"No. A consistency protocol also needs durable ordering, authority and membership rules; define the guarantee and failure policy of each operation.","objective":"Choose per-operation consistency and failure behavior instead of treating CAP as a product rating.","question":"During a network partition, what policy must be explicit beyond merely counting replies?","references":["https://raft.github.io/raft.pdf","https://www.cs.columbia.edu/~wing/publications/HerlihyWing90.pdf","https://go.dev/ref/mem"],"reviewAnswer":"State which operations may proceed and reconcile","reviewPrompt":"Partition-time consistency","sections":[{"body":"A network partition can prevent replicas from coordinating. Whether a particular operation may proceed depends on the required consistency contract and the available authority, not on whether the service was written in Go or has a cache. Specify which reads may be stale, which writes require a leader or quorum, and what the caller sees when that requirement cannot be met.","title":"The contract and the failure"},{"body":"State requirements per use case: a cached catalog may tolerate lag, while spending a balance or reserving an account nonce may require serialized authority. Define read-your-writes behavior, version checks and reconciliation for replicas or projections. Distinguish the availability/consistency tradeoff during a partition from ordinary latency and throughput tradeoffs even when the network is healthy.","code":"package main\n\nimport \"fmt\"\n\nfunc majority(replicas, acks int) bool {\n\treturn replicas > 0 && acks >= replicas/2+1 && acks <= replicas\n}\nfunc main() { fmt.Println(majority(5, 2), majority(5, 3)) }\n\n// Threshold arithmetic only: this is not a consensus or replication algorithm.","language":"go","title":"Work through the example","walkthrough":"Three acknowledgements meet a simple majority threshold for five configured replicas; two do not. The predicate demonstrates arithmetic only. Real consensus also needs terms, log ordering, membership changes, persistence and safety rules. Counting arbitrary replies does not prove a linearizable write or that a stale leader cannot act."},{"body":"Do not claim that a system simply chooses any two of consistency, availability and partition tolerance. A timestamp or a mutex in each replica does not establish a global order. A quorum slogan does not replace a protocol or fault test. Demonstrate split connectivity, stale leadership, concurrent writes, membership changes and recovery, then explain the exact guarantee your operation can still make.","title":"Production decisions"},{"body":"Does a majority-count helper by itself implement linearizable distributed storage? No. A consistency protocol also needs durable ordering, authority and membership rules; define the guarantee and failure policy of each operation. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Choose per-operation consistency and failure behavior instead of treating CAP as a product rating. No. A consistency protocol also needs durable ordering, authority and membership rules; define the guarantee and failure policy of each operation.","title":"Consistency under partitions: explain an operation, not a slogan","unitID":"system-design","wrongAnswers":["A local mutex orders writes across replicas","Counting replies implements a consensus algorithm"]}],"revision":"2026-11-18.1","schemaVersion":1,"solutions":{"collections.append-aliasing":"package main\n\nfunc window(s []int) []int {\n\treturn s[1:3:3]\n}\n\nfunc main() {}","collections.arrays":"package main\n\nfunc FirstThree(values [4]int) [3]int {\n\treturn [3]int{values[0], values[1], values[2]}\n}\n\nfunc main() {}","collections.function-values":"package main\n\nfunc Apply(values []int, fn func(int) int) []int {\n\tout := make([]int, len(values))\n\tfor i, v := range values {\n\t\tout[i] = fn(v)\n\t}\n\treturn out\n}\n\nfunc main() {}","collections.iterators":"package main\n\nfunc Take(values []string, n int) func(func(string) bool) {\n\treturn func(yield func(string) bool) {\n\t\tfor i, value := range values {\n\t\t\tif i >= n {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif !yield(value) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tfor value := range Take([]string{\"go\", \"forge\", \"run\"}, 2) {\n\t\tprintln(value)\n\t}\n}","collections.make-and-new":"package main\n\nfunc ReadyMap() map[string]int { return make(map[string]int) }\nfunc ZeroCounter() *int        { return new(int) }\n\nfunc main() {}","collections.map-ok":"package main\n\nfunc Has(m map[string]int, key string) bool {\n\t_, ok := m[key]\n\treturn ok\n}\n\nfunc main() {}","collections.map-order":"package main\n\nimport \"slices\"\n\nfunc SortedKeys(m map[string]int) []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\tslices.Sort(keys)\n\treturn keys\n}\n\nfunc main() {}","collections.map-zero-value":"package main\n\nfunc countWords(words []string) map[string]int {\n\tcounts := make(map[string]int, len(words))\n\tfor _, word := range words {\n\t\tcounts[word]++\n\t}\n\treturn counts\n}\n\nfunc main() {}","collections.strings-builder":"package main\n\nimport \"strings\"\n\nfunc Repeat(word string, n int) string {\n\tvar b strings.Builder\n\tfor i := 0; i < n; i++ {\n\t\tif i > 0 {\n\t\t\tb.WriteByte(' ')\n\t\t}\n\t\tb.WriteString(word)\n\t}\n\treturn b.String()\n}\n\nfunc main() {}","concurrency.buffered":"package main\n\nfunc Fill(n int) []int {\n\tch := make(chan int, n)\n\tfor i := 0; i < n; i++ {\n\t\tch <- i\n\t}\n\tclose(ch)\n\tout := make([]int, 0, n)\n\tfor v := range ch {\n\t\tout = append(out, v)\n\t}\n\treturn out\n}\n\nfunc main() {}","concurrency.channel-close":"package main\n\nfunc squares(n int) <-chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tdefer close(out)\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tout <- i * i\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc main() {}","concurrency.direction":"package main\n\nfunc Produce(out chan<- int, values []int) {\n\tdefer close(out)\n\tfor _, v := range values {\n\t\tout <- v\n\t}\n}\n\nfunc main() {}","concurrency.mutex":"package main\n\nimport \"sync\"\n\ntype Counter struct {\n\tmu    sync.Mutex\n\tcount map[string]int\n}\n\nfunc NewCounter() *Counter {\n\treturn &Counter{count: map[string]int{}}\n}\n\nfunc (c *Counter) Add(key string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.count[key]++\n}\n\nfunc (c *Counter) Get(key string) int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.count[key]\n}\n\nfunc main() {}","concurrency.once":"package main\n\nimport \"sync\"\n\nfunc Call(once *sync.Once, fn func()) {\n\tonce.Do(fn)\n}\n\nfunc main() {}","concurrency.range-and-close":"package main\n\nfunc Drain(ch <-chan int) []int {\n\tout := []int{}\n\tfor v := range ch {\n\t\tout = append(out, v)\n\t}\n\treturn out\n}\n\nfunc main() {}","concurrency.select-context":"package main\n\nimport \"context\"\n\nfunc waitFor(ctx context.Context, values <-chan int) (int, error) {\n\tselect {\n\tcase value := <-values:\n\t\treturn value, nil\n\tcase <-ctx.Done():\n\t\treturn 0, ctx.Err()\n\t}\n}\n\nfunc main() {}","concurrency.select-default":"package main\n\nfunc TryRecv(ch <-chan int) (int, bool) {\n\tselect {\n\tcase v := <-ch:\n\t\treturn v, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}\n\nfunc main() {}","concurrency.worker-pool":"package main\n\nimport \"sync\"\n\nfunc Squares(numbers []int, workers int) []int {\n\tin, out := make(chan int), make(chan int)\n\n\tvar wg sync.WaitGroup\n\tfor range workers {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor n := range in {\n\t\t\t\tout <- n * n\n\t\t\t}\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tdefer close(in)\n\t\tfor _, n := range numbers {\n\t\t\tin <- n\n\t\t}\n\t}()\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\n\tresults := make([]int, 0, len(numbers))\n\tfor r := range out {\n\t\tresults = append(results, r)\n\t}\n\treturn results\n}\n\nfunc main() {}","core.conversions":"package main\n\ntype Celsius float64\n\nfunc Average(readings []Celsius) Celsius {\n\tvar sum Celsius\n\tfor _, r := range readings {\n\t\tsum += r\n\t}\n\treturn sum / Celsius(len(readings))\n}\n\nfunc main() {}","core.multiple-returns":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\nvar errOdd = errors.New(\"value is odd\")\n\nfunc half(n int) (int, error) {\n\tif n%2 != 0 {\n\t\treturn 0, fmt.Errorf(\"half %d: %w\", n, errOdd)\n\t}\n\treturn n / 2, nil\n}\n\nfunc main() {\n\tvalue, err := half(9)\n\tfmt.Println(value, err)\n}","core.named-results":"package main\n\nfunc Split(n, d int) (quot, rem int) {\n\tquot = n / d\n\trem = n % d\n\treturn\n}\n\nfunc main() {}","core.switch":"package main\n\nfunc Classify(n int) string {\n\tswitch {\n\tcase n < 10:\n\t\treturn \"small\"\n\tcase n < 100:\n\t\treturn \"medium\"\n\tdefault:\n\t\treturn \"large\"\n\t}\n}\n\nfunc main() {}","core.unused-is-an-error":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\thost := \"localhost\"\n\tport := 8080\n\tfmt.Println(host, port)\n}","errors.custom-type":"package main\n\nimport \"fmt\"\n\ntype ParseError struct {\n\tField  string\n\tReason string\n}\n\nfunc (e *ParseError) Error() string {\n\treturn fmt.Sprintf(\"field %q: %s\", e.Field, e.Reason)\n}\n\nfunc Parse(field, value string) error {\n\tif field == \"\" {\n\t\treturn &ParseError{Field: field, Reason: \"name is empty\"}\n\t}\n\treturn nil\n}\n\nfunc main() {}","errors.recover":"package main\n\nimport \"fmt\"\n\nfunc Guard(work func()) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"panic: %v\", r)\n\t\t}\n\t}()\n\twork()\n\treturn nil\n}\n\nfunc main() {}","errors.wrapping":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n)\n\nvar ErrNotANumber = errors.New(\"not a number\")\n\nfunc parsePort(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"parse port %q: %w\", raw, ErrNotANumber)\n\t}\n\treturn n, nil\n}\n\nfunc main() {}","generics.constraints":"package main\n\n// The tilde is what lets a named type through: a type whose underlying\n// type is float64 satisfies ~float64, and without it the constraint\n// would accept only float64 itself.\ntype Number interface {\n\t~int | ~int8 | ~int16 | ~int32 | ~int64 |\n\t~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |\n\t~float32 | ~float64 | ~complex64 | ~complex128\n}\n\nfunc Sum[T Number](values []T) T {\n\tvar total T\n\tfor _, value := range values {\n\t\ttotal += value\n\t}\n\treturn total\n}\n\nfunc main() {\n\tprintln(Sum([]int{1, 2, 3}))\n}","generics.containers":"package main\n\ntype Stack[T any] struct {\n\titems []T\n}\n\nfunc (s *Stack[T]) Push(value T) {\n\t// A nil slice appends fine, which is what makes the zero value work.\n\ts.items = append(s.items, value)\n}\n\nfunc (s *Stack[T]) Pop() (T, bool) {\n\tif len(s.items) == 0 {\n\t\t// The zero value of T, whatever T turned out to be.\n\t\tvar zero T\n\t\treturn zero, false\n\t}\n\tlast := len(s.items) - 1\n\tvalue := s.items[last]\n\tvar zero T\n\ts.items[last] = zero\n\ts.items = s.items[:last]\n\treturn value, true\n}\n\nfunc main() {\n\tvar s Stack[string]\n\ts.Push(\"go\")\n\tvalue, ok := s.Pop()\n\tprintln(value, ok)\n}","generics.methods":"package main\n\ntype Bag[E any] struct {\n\titems []E\n}\n\nfunc (b Bag[E]) Map[F any](f func(E) F) Bag[F] {\n\tmapped := make([]F, 0, len(b.items))\n\tfor _, item := range b.items {\n\t\tmapped = append(mapped, f(item))\n\t}\n\treturn Bag[F]{items: mapped}\n}\n\nfunc main() {\n\tb := Bag[int]{items: []int{1, 2, 3}}\n\tprintln(len(b.Map(func(n int) string { return \"x\" }).items))\n}","generics.type-parameters":"package main\n\nfunc Keep[T any](in []T, keep func(T) bool) []T {\n\tvar out []T\n\tfor _, value := range in {\n\t\tif keep(value) {\n\t\t\tout = append(out, value)\n\t\t}\n\t}\n\treturn out\n}\n\nfunc main() {\n\teven := Keep([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })\n\tprintln(len(even))\n}","interfaces.empty":"package main\n\nimport \"fmt\"\n\nfunc Kind(value any) string {\n\treturn fmt.Sprintf(\"%T\", value)\n}\n\nfunc main() {}","interfaces.implicit":"package main\n\ntype sized interface {\n\tLen() int\n}\n\nfunc summarise(s sized) int {\n\treturn s.Len()\n}\n\nfunc main() {}","interfaces.stringer":"package main\n\nimport \"fmt\"\n\ntype IPAddr [4]byte\n\nfunc (ip IPAddr) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\", ip[0], ip[1], ip[2], ip[3])\n}\n\nfunc main() {}","interfaces.type-switch":"package main\n\nimport \"fmt\"\n\nfunc Describe(value any) string {\n\tswitch v := value.(type) {\n\tcase int:\n\t\treturn fmt.Sprintf(\"int %d\", v)\n\tcase string:\n\t\treturn fmt.Sprintf(\"string %s\", v)\n\tcase bool:\n\t\treturn fmt.Sprintf(\"bool %t\", v)\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc main() { fmt.Println(Describe(7)) }","modules.tests":"package main\n\nfunc Clamp(value, low, high int) int {\n\tif value < low {\n\t\treturn low\n\t}\n\tif value > high {\n\t\treturn high\n\t}\n\treturn value\n}\n\nfunc main() {}","stdlib.context":"package main\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\nfunc WaitFor(ctx context.Context, d time.Duration) error {\n\ttimer := time.NewTimer(d)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\nfunc main() {}","stdlib.http":"package main\n\nimport (\n\t\"io\"\n\t\"net/http\"\n)\n\nfunc Hello() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"/hello\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tio.WriteString(w, \"hi\")\n\t})\n}\n\nfunc main() {}","stdlib.image":"package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n)\n\ntype Solid struct {\n\tW, H int\n\tC    color.RGBA\n}\n\nfunc (s Solid) ColorModel() color.Model { return color.RGBAModel }\n\nfunc (s Solid) Bounds() image.Rectangle {\n\treturn image.Rect(0, 0, s.W, s.H)\n}\n\nfunc (s Solid) At(x, y int) color.Color { return s.C }\n\nfunc main() {}","stdlib.io":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\nfunc WriteUpper(dst io.Writer, src io.Reader) error {\n\tdata, err := io.ReadAll(src)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read: %w\", err)\n\t}\n\tif _, err := io.WriteString(dst, strings.ToUpper(string(data))); err != nil {\n\t\treturn fmt.Errorf(\"write: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc main() {}","stdlib.sort":"package main\n\nimport (\n\t\"cmp\"\n\t\"slices\"\n)\n\ntype Release struct {\n\tName string\n\tYear int\n}\n\nfunc SortReleases(releases []Release) {\n\tslices.SortFunc(releases, func(a, b Release) int {\n\t\tif c := cmp.Compare(a.Year, b.Year); c != 0 {\n\t\t\treturn c\n\t\t}\n\t\treturn cmp.Compare(a.Name, b.Name)\n\t})\n}\n\nfunc main() {}","stdlib.strconv":"package main\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n)\n\nfunc ParsePort(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif n < 1 || n > 65535 {\n\t\treturn 0, fmt.Errorf(\"port %d out of range\", n)\n\t}\n\treturn n, nil\n}\n\nfunc main() {}","structs.closures":"package main\n\nfunc Counter() func() int {\n\t// Declared inside Counter, so every call to Counter gets its own.\n\tcount := 0\n\treturn func() int {\n\t\tcount++\n\t\treturn count\n\t}\n}\n\nfunc main() {\n\tnext := Counter()\n\tprintln(next(), next())\n}","structs.literals":"package main\n\ntype Rect struct {\n\tWidth  int\n\tHeight int\n}\n\nfunc Area(r Rect) int {\n\treturn r.Width * r.Height\n}\n\nfunc main() {\n\tprintln(Area(Rect{Width: 3, Height: 4}))\n}","structs.methods":"package main\n\ntype Counter struct {\n\tTotal int\n}\n\n// A pointer receiver, because the method changes the receiver and the\n// caller has to see it.\nfunc (c *Counter) Add(n int) {\n\tc.Total += n\n}\n\nfunc (c *Counter) Value() int {\n\treturn c.Total\n}\n\nfunc main() {\n\tc := Counter{}\n\tc.Add(3)\n\tprintln(c.Value())\n}"},"units":[{"id":"core","lessons":[{"conceptTags":["vars.unused"],"explanation":"Every Go variable starts at its type's zero value: `0` for numbers, `\"\"` for strings, `false` for booleans, and `nil` for pointers, slices, maps, channels, functions and interfaces. A declaration gives you a defined value immediately.\n\nA struct starts with every field at its own zero value. Design that state to be useful when possible: counters and slices work naturally, while a map field still needs initialization before a write. A `New` function is useful when the type requires setup that its zero value cannot provide.","id":"core.zero-values","objective":"Predict the value of any declared variable before it is assigned.","task":{"predict":{"answer":"0 \"\" true 0\n\nThe zero value of a slice is nil. Its length and capacity are 0. You can range over it or append to it; append returns the resulting slice. Indexing the empty slice to read or write an element is out of bounds.","question":"What does this print, and why does len work on a nil slice?","source":"package main\n\nimport \"fmt\"\n\ntype Counter struct {\n\tTotal int\n\tLabel string\n\tTags  []string\n}\n\nfunc main() {\n\tvar c Counter\n\tfmt.Printf(\"%d %q %v %d\\n\", c.Total, c.Label, c.Tags == nil, len(c.Tags))\n}"}},"title":"Nothing is uninitialised"},{"conceptTags":["vars.short-declaration"],"explanation":"`:=` declares and assigns in one step inside a function. At least one non-blank name on the left must be new in the current block; otherwise the compiler reports \"no new variables\".\n\nA short declaration may mix new names with names already declared in that same block. Inside a nested block, however, it may introduce a different variable with the same spelling. Use `=` when the intention is to update an existing variable.","id":"core.short-declaration","objective":"Choose between := and = without guessing, and know when := is illegal.","task":{"guidedTyping":{"target":"value, err := parse(input)\nif err != nil {\n\treturn err\n}"}},"title":":= declares, = assigns"},{"conceptTags":["vars.short-declaration"],"explanation":"A useful way to read Go is to ask three questions at each assignment: which block owns this name, what type does it have, and is a new variable being created? The spelling of a name alone does not answer any of them.","id":"core.declarations-walkthrough","objective":"Follow values through a short declaration, an assignment and a shadowed name without running the program.","task":{"reading":{}},"title":"Read a declaration one scope at a time"},{"conceptTags":["errors.explicit-check"],"explanation":"An error result is part of a function contract. The caller needs to know whether a value is valid when err is non-nil, who should add context, and which layer decides what the user sees. A short early return makes that contract visible.","id":"core.error-path-walkthrough","objective":"Trace a result and error through a complete boundary, including wrapping and partial results.","task":{"reading":{}},"title":"Read the failure path before the happy path"},{"conceptTags":["errors.explicit-check","functions.missing-return"],"explanation":"Go functions can return several values. A common fallible signature returns a result followed by `error`; callers inspect that error before continuing with the result.\n\nThis makes ordinary failures explicit at the call site instead of using exceptions. Go also has `panic` and `recover` for exceptional control flow, but an error result is the usual contract for an expected failure. Short failure branches keep the successful path easy to read.","id":"core.multiple-returns","idiomaticSolution":"func half(n int) (int, error) {\n\tif n%2 != 0 {\n\t\treturn 0, fmt.Errorf(\"half %d: %w\", n, errOdd)\n\t}\n\treturn n / 2, nil\n}","objective":"Write a function that returns a result and an error, and read one.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestHalfEven(t *testing.T) {\n\tgot, err := half(8)\n\tif err != nil {\n\t\tt.Fatalf(\"half(8) returned %v\", err)\n\t}\n\tif got != 4 {\n\t\tt.Errorf(\"half(8) = %d, want 4\", got)\n\t}\n}\n\nfunc TestHalfOdd(t *testing.T) {\n\tif _, err := half(9); err == nil {\n\t\tt.Fatal(\"half(9) returned no error\")\n\t}\n\tif _, err := half(9); !errors.Is(err, errOdd) {\n\t\tt.Errorf(\"half(9) error = %v, want errOdd\", err)\n\t}\n}","starter":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// half returns n divided by two, and an error when n is odd.\nfunc half(n int) (int, error) {\n\t// TODO: return an error when n is odd, otherwise the halved value.\n\treturn 0, nil\n}\n\nfunc main() {\n\tvalue, err := half(9)\n\tfmt.Println(value, err)\n}\n\nvar errOdd = errors.New(\"value is odd\")"}},"title":"Two returns instead of one exception"},{"conceptTags":["vars.unused","modules.unused-import"],"explanation":"Go refuses to compile a function with a variable it never reads, and a file with an import it never uses. Not a warning — an error.\n\nThis feels hostile for about a week. What it buys is that dead code cannot accumulate quietly, and that a half-finished edit fails loudly instead of shipping. The escape hatch when you genuinely need it is assignment to _, which says \"deliberately discarded\" out loud.","id":"core.unused-is-an-error","idiomaticSolution":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\thost := \"localhost\"\n\tport := 8080\n\tfmt.Println(host, port)\n}","objective":"Recognise the two unused errors on sight and know why they exist.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\n// The lesson passes when the package compiles at all: the starter\n// has both an unused variable and an unused import.\nfunc TestCompiles(t *testing.T) {}","starter":"package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\thost := \"localhost\"\n\tport := 8080\n\tfmt.Println(port)\n}"}},"title":"An unused variable stops the build"},{"conceptTags":["types.constants"],"explanation":"An untyped constant in Go has arbitrary precision and no type until it is used. `const big = 1 << 62` is fine even where an int is 32 bits, because nothing has asked it to become an int yet. The moment it is assigned or passed, it takes the type it is needed as — and that is where it can fail to fit.\n\n`iota` is the other half. Inside a const block it counts from zero, one step per line, which is how Go writes enumerations without an enum keyword. The idiom is worth recognising on sight: a type, a const block with iota, and often a String method.","id":"core.constants","objective":"Explain why 1 << 40 compiles as a constant but overflows as an int32.","task":{"predict":{"answer":"0 1 2 3\n1024","question":"What does this print?","source":"package main\n\nimport \"fmt\"\n\ntype Level int\n\nconst (\n\tDebug Level = iota\n\tInfo\n\tWarn\n\tError\n)\n\nfunc main() {\n\tfmt.Println(Debug, Info, Warn, Error)\n\tconst big = 1 << 40\n\tfmt.Println(big / 1024 / 1024 / 1024)\n}"}},"title":"Constants have no type until they need one"},{"conceptTags":["control.switch"],"explanation":"In C, Java and JavaScript a case runs on into the next one unless you write `break`. Go inverted that: a case ends at the next case, and `fallthrough` is the keyword you write on the rare occasion you want the old behaviour. You do not need `break` just to end a case, though an explicit `break` can leave a switch early.\n\nTwo more differences worth having: a case can list several values separated by commas, and a switch with no expression is a tidy way to write a chain of conditions.","id":"core.switch","idiomaticSolution":"func Classify(n int) string {\n\tswitch {\n\tcase n < 10:\n\t\treturn \"small\"\n\tcase n < 100:\n\t\treturn \"medium\"\n\tdefault:\n\t\treturn \"large\"\n\t}\n}","objective":"Write a Go switch without reaching for break.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestClassify(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin   int\n\t\twant string\n\t}{{0, \"small\"}, {9, \"small\"}, {10, \"medium\"}, {99, \"medium\"}, {100, \"large\"}} {\n\t\tif got := Classify(c.in); got != c.want {\n\t\t\tt.Errorf(\"Classify(%d) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}","starter":"package main\n\n// Classify returns \"small\" for n under 10, \"medium\" under 100,\n// and \"large\" otherwise. Write it with a switch that has no\n// expression after the keyword.\nfunc Classify(n int) string {\n\treturn \"\"\n}\n\nfunc main() {}"}},"title":"switch does not fall through"},{"conceptTags":["types.assignment","types.conversion"],"explanation":"There is no implicit numeric conversion in Go. An int and an int64 are different types even where they are the same width, and adding them is an error rather than a promotion. The fix is always an explicit conversion, and the point of the rule is that the place where precision could be lost is visible in the source.\n\nA named type behaves the same way. `type Celsius float64` cannot be added to a float64 without saying so, which is exactly what makes named types worth declaring: the compiler stops you mixing units.","id":"core.conversions","idiomaticSolution":"return sum / Celsius(len(readings))","objective":"Fix a mismatched-type expression without guessing.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestAverage(t *testing.T) {\n\tif got := Average([]Celsius{10, 20, 30}); got != 20 {\n\t\tt.Errorf(\"Average = %v, want 20\", got)\n\t}\n\tif got := Average([]Celsius{1, 2}); got != 1.5 {\n\t\tt.Errorf(\"Average = %v, want 1.5\", got)\n\t}\n}","starter":"package main\n\ntype Celsius float64\n\n// Average returns the mean of the readings, in Celsius.\n// count is an int and the sum is a Celsius; make them agree.\nfunc Average(readings []Celsius) Celsius {\n\tvar sum Celsius\n\tfor _, r := range readings {\n\t\tsum += r\n\t}\n\treturn sum / len(readings)\n}\n\nfunc main() {}"}},"title":"Go never converts a number for you"},{"conceptTags":["functions.named-results","functions.missing-return"],"explanation":"Names in a function's result list declare local result variables initialized to zero. A bare `return` returns their current values. In a short helper, names such as `quot` and `rem` can explain which result is which.\n\nAn explicit `return quot, rem` is often easier to review once a function has branches. Result names document intent, but the compiler does not protect two same-typed results from being swapped. A deferred closure may change named results before the function returns to its caller.","id":"core.named-results","idiomaticSolution":"func Split(n, d int) (quot, rem int) {\n\tquot = n / d\n\trem = n % d\n\treturn\n}","objective":"Write a short function that uses a naked return, and know when not to.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestSplit(t *testing.T) {\n\tquot, rem := Split(17, 5)\n\tif quot != 3 || rem != 2 {\n\t\tt.Fatalf(\"Split(17, 5) = %d, %d; want 3, 2\", quot, rem)\n\t}\n\tquot, rem = Split(-9, 4)\n\tif quot != -2 || rem != -1 {\n\t\tt.Fatalf(\"Split(-9, 4) = %d, %d; want -2, -1\", quot, rem)\n\t}\n}","starter":"package main\n\n// Split returns n / d and n % d. Name the results and use a\n// naked return. Do not guard against d == 0; the test never\n// passes zero.\nfunc Split(n, d int) (int, int) {\n\treturn 0, 0\n}\n\nfunc main() {}"}},"title":"A return can name what it is handing back"},{"conceptTags":["errors.defer"],"explanation":"Deferred calls run in last-in, first-out order when the surrounding function returns. Three `defer fmt.Println(n)` statements execute in the reverse of their registration order.\n\nThe deferred function and its arguments are evaluated when `defer` executes. A deferred closure, in contrast, may read a captured variable when it eventually runs. Keep that distinction clear when a variable changes between registration and return.","id":"core.defer-stack","objective":"Say the print order of three deferred calls.","task":{"predict":{"answer":"counting\ndone\n2\n1\n0","question":"What does this print? The Tour's stacking-defers program.","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfmt.Println(\"counting\")\n\tfor i := 0; i < 3; i++ {\n\t\tdefer fmt.Println(i)\n\t}\n\tfmt.Println(\"done\")\n}"}},"title":"Deferred calls stack, last one first"}],"summary":"Declarations, zero values, multiple returns and the shapes Go repeats everywhere.","title":"Go core","translationNote":"Most of this unit is not new material — it is unlearning. Go has no built-in class constructors or exception-handling syntax, and declared variables start with zero values, so habits from Java, C# and Python each need one specific adjustment rather than a general rewrite."},{"id":"structs","lessons":[{"conceptTags":["types.struct-literal"],"explanation":"A struct groups fields under a type name. `Point{X: 1, Y: 2}` names its fields; `Point{1, 2}` relies on declaration order. Reordering same-typed fields can silently change an unkeyed literal's meaning. Adding a field usually makes an existing unkeyed literal fail to compile. Keyed literals make intent clearer, and vet checks unkeyed literals for structs from other packages.\n\nA struct's zero value is a struct, not nil. Each field begins at its own zero value. Fields beginning with an uppercase letter are exported; visibility is decided per field.","id":"structs.literals","idiomaticSolution":"type Rect struct {\n\tWidth  int\n\tHeight int\n}\n\nfunc Area(r Rect) int {\n\treturn r.Width * r.Height\n}","objective":"Declare a struct type and build values of it without positional guessing.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestArea(t *testing.T) {\n\tcases := []struct {\n\t\tname string\n\t\tin   Rect\n\t\twant int\n\t}{\n\t\t{name: \"three by four\", in: Rect{Width: 3, Height: 4}, want: 12},\n\t\t{name: \"zero value\", in: Rect{}, want: 0},\n\t\t{name: \"one side\", in: Rect{Width: 5}, want: 0},\n\t}\n\tfor _, testCase := range cases {\n\t\tt.Run(testCase.name, func(t *testing.T) {\n\t\t\tif got := Area(testCase.in); got != testCase.want {\n\t\t\t\tt.Errorf(\"Area(%+v) = %d, want %d\", testCase.in, got, testCase.want)\n\t\t\t}\n\t\t})\n\t}\n}","starter":"package main\n\n// Declare a Rect type with Width and Height fields of type int,\n// then finish Area so it returns their product.\n\nfunc Area(r Rect) int {\n\treturn 0\n}\n\nfunc main() {\n\tprintln(Area(Rect{Width: 3, Height: 4}))\n}"}},"title":"A struct is data, and its fields have names"},{"conceptTags":["types.pointer","interfaces.method-set"],"explanation":"A method is declared outside the type, with the receiver in parentheses before the name: `func (r Rect) Area() int`. There is no class body, and methods can be attached to any type you declared in this package — including `type Celsius float64`, not only structs.\n\nThe receiver is a copy unless it is a pointer. `func (r Rect) Grow()` mutates a copy and the caller sees nothing; `func (r *Rect) Grow()` mutates the original. Go calls either form for you — `r.Grow()` works on an addressable value whichever receiver you chose — so the compiler will not warn you that the mutation went nowhere.\n\nThe convention is to pick one kind of receiver for the whole type. A type with some value methods and some pointer methods has a method set that changes depending on whether you hold a value or a pointer, and that is where \"it does not satisfy the interface\" comes from.","id":"structs.methods","idiomaticSolution":"// A pointer receiver, because the method changes the receiver and the\n// caller has to see it.\nfunc (c *Counter) Add(n int) {\n\tc.Total += n\n}\n\n// A pointer receiver here too, not because it mutates but because a\n// type is easier to reason about when all its methods agree.\nfunc (c *Counter) Value() int {\n\treturn c.Total\n}","objective":"Put a method on your own type and choose the receiver deliberately.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestAddIsVisibleToTheCaller(t *testing.T) {\n\tc := Counter{}\n\tc.Add(3)\n\tc.Add(4)\n\tif got := c.Value(); got != 7 {\n\t\tt.Errorf(\"after adding 3 and 4, Value() = %d, want 7\", got)\n\t}\n}\n\nfunc TestZeroValueIsUsable(t *testing.T) {\n\tvar c Counter\n\tif got := c.Value(); got != 0 {\n\t\tt.Errorf(\"a fresh Counter reports %d, want 0\", got)\n\t}\n}","starter":"package main\n\ntype Counter struct {\n\tTotal int\n}\n\n// Add should increase the counter by n, and the change must be\n// visible to the caller. Total should report the current value.\n\nfunc main() {\n\tc := Counter{}\n\tc.Add(3)\n\tprintln(c.Value())\n}"}},"title":"A method is a function with a receiver"},{"conceptTags":["types.pointer"],"explanation":"Go passes everything by value. A struct handed to a function is copied, and writing to the copy changes nothing the caller can see. A pointer is how you say \"the same one\", and `&` and `*` are the whole syntax: `&value` takes an address, `*pointer` reads through one. Field access needs no `*` — `p.X` works on a pointer as well as a value, which is why you rarely see the star in ordinary code.\n\nThere is no pointer arithmetic. A Go pointer either points at something or is nil, and that is all it can do — which is why passing one is safe in a way it is not in C.\n\nThe reason to use one is mutation. \"Pointers are faster\" is a guess: for a small struct the copy is often cheaper than the indirection and the extra work the garbage collector inherits. Measure before believing it, and until you have, choose based on whether the callee needs to change what it was given.","id":"structs.pointers","objective":"Say when a pointer is required and when it is only noise.","task":{"predict":{"answer":"1, then 9.\n\nbyValue was handed a copy of the struct. It set Retries on the copy,\nthe copy went out of scope, and the caller's value never changed —\nthe compiler says nothing, because assigning to your own parameter\nis perfectly legal.\n\nbyPointer was handed the address, so `s.Retries = 9` wrote through\nto the original. Note that neither function needed a `*` to reach\nthe field: Go dereferences for you on field access.","question":"What are the two numbers, and why are they different?","source":"package main\n\nimport \"fmt\"\n\ntype Settings struct {\n\tRetries int\n}\n\nfunc byValue(s Settings) {\n\ts.Retries = 9\n}\n\nfunc byPointer(s *Settings) {\n\ts.Retries = 9\n}\n\nfunc main() {\n\ts := Settings{Retries: 1}\n\tbyValue(s)\n\tfmt.Println(s.Retries)\n\tbyPointer(&s)\n\tfmt.Println(s.Retries)\n}"}},"title":"A pointer is for changing something, not for speed"},{"conceptTags":["functions.closure"],"explanation":"Functions are values: they can be stored, passed and returned. A function literal keeps access to the variables it captures, rather than taking an automatic snapshot of their values.\n\nTwo closures capturing the same variable see each other's updates. Separate calls to a factory create separate environments. When you need a snapshot, make an explicit copy for the closure to capture.\n\nSince Go 1.22, iteration variables declared by a loop get a fresh variable on each iteration. A loop assigning to a variable declared outside it still reuses that variable. The distinction between `:=` and `=` matters here too.","id":"structs.closures","idiomaticSolution":"func Counter() func() int {\n\t// Declared inside Counter, so every call to Counter gets its own.\n\tcount := 0\n\treturn func() int {\n\t\tcount++\n\t\treturn count\n\t}\n}","objective":"Return a function that carries state, and know what it captured.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestCounterCountsUp(t *testing.T) {\n\tnext := Counter()\n\tfor want := 1; want <= 3; want++ {\n\t\tif got := next(); got != want {\n\t\t\tt.Fatalf(\"call %d returned %d\", want, got)\n\t\t}\n\t}\n}\n\nfunc TestTwoCountersAreIndependent(t *testing.T) {\n\tfirst := Counter()\n\tsecond := Counter()\n\tfirst()\n\tfirst()\n\tif got := second(); got != 1 {\n\t\tt.Errorf(\"a fresh counter returned %d, want 1; the two share state\", got)\n\t}\n}","starter":"package main\n\n// Counter should return a function that returns 1 the first time it\n// is called, 2 the second time, and so on. Two counters made by two\n// calls must not share their count.\n\nfunc main() {\n\tnext := Counter()\n\tprintln(next(), next())\n}"}},"title":"A function is a value, and it remembers where it came from"},{"conceptTags":["types.pointer"],"explanation":"In C this is the classic mistake: return the address of a local and the stack frame is gone by the time the caller looks. Go removes the mistake rather than warning about it. The compiler works out that the value outlives the function — escape analysis — and allocates it somewhere that survives.\n\nSo `return &Config{}` is ordinary, idiomatic Go, and constructors called `New...` do it constantly. You are not choosing stack or heap; the compiler is, from how the value is used.\n\nWhat this does *not* mean is that pointers are free. An escaping value becomes garbage collector work, which is the real cost behind \"pointers are faster\" being a guess rather than a rule.","id":"structs.escape","objective":"Explain why Go lets you return the address of a local variable.","task":{"predict":{"answer":"It compiles, and prints: a b false\n\n`local` escapes, so the compiler allocates it where it can outlive\nthe call. Every call to New produces a distinct value, so the two\npointers are different and `first == second` is false — pointer\ncomparison asks whether they point at the same thing, not whether\nthe things are equal.","question":"Does this compile, and what does it print?","source":"package main\n\nimport \"fmt\"\n\ntype Config struct {\n\tName string\n}\n\nfunc New(name string) *Config {\n\tlocal := Config{Name: name}\n\treturn &local\n}\n\nfunc main() {\n\tfirst := New(\"a\")\n\tsecond := New(\"b\")\n\tfmt.Println(first.Name, second.Name, first == second)\n}"}},"title":"Returning a pointer to a local is fine"}],"summary":"Structs, methods, pointers, and functions that are values.","title":"Types you define","translationNote":"There is no class here and nothing to inherit from. A struct is data, a method is a function with a receiver written before its name, and the two are declared separately — which means you can put methods on any type you define, not only on structs.\n\nThe habit to unlearn is reaching for a pointer by default. In Go a value is copied unless you say otherwise, and that is usually what you want; a pointer is for when the method has to change the thing it was called on, or when copying it would genuinely cost."},{"id":"collections","lessons":[{"conceptTags":["slices.aliasing"],"explanation":"A slice describes a region of an array. Copying a slice value copies its descriptor, not all the elements. Two descriptors may therefore refer to the same elements while having different lengths and capacities.","id":"collections.slice-walkthrough","objective":"Predict a subslice, an element write and append by tracking the backing array.","task":{"reading":{}},"title":"A slice is a window, not a copied array"},{"conceptTags":["slices.capacity"],"explanation":"A slice is three words: a pointer to an array, a length and a capacity. append writes into the existing array while the capacity allows it, and allocates a new one when it does not.\n\nThat single rule explains most slice surprises: whether a write is seen by another slice depends on whether an append happened to reallocate.","id":"collections.length-capacity","objective":"Predict when append allocates and when it writes in place.","task":{"predict":{"answer":"2 4, then 5 8.\n\nThe first append fits in the capacity that was already reserved. The second exceeds it, so the runtime allocates a larger array — the growth factor is an implementation detail, but the doubling to 8 is what current Go does for small slices.","question":"What are the two length and capacity pairs?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := make([]int, 0, 4)\n\ts = append(s, 1, 2)\n\tfmt.Println(len(s), cap(s))\n\ts = append(s, 3, 4, 5)\n\tfmt.Println(len(s), cap(s))\n}"}},"title":"len is what you have, cap is what you can grow into"},{"conceptTags":["slices.aliasing","slices.capacity"],"explanation":"Slicing does not copy elements. `s[1:3]` refers to the same backing array, so writes to overlapping elements are visible through both slices. An append that allocates a new array detaches the returned slice from that old storage.\n\nA full slice expression such as `s[1:3:3]` limits capacity, forcing an append of another element to allocate. It does not detach the elements already in the view. Use `copy` or `slices.Clone` when the result must be independently mutable.","id":"collections.append-aliasing","idiomaticSolution":"func window(s []int) []int {\n\treturn s[1:3:3]\n}","objective":"Spot the moment a subslice starts sharing writes with its parent.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestWindowDoesNotShareCapacity(t *testing.T) {\n\toriginal := []int{1, 2, 3, 4, 5}\n\tw := window(original)\n\tw = append(w, 99)\n\tif original[3] == 99 {\n\t\tt.Fatal(\"append through the window overwrote the parent slice\")\n\t}\n}","starter":"package main\n\n// window returns the middle of s without letting the caller's\n// appends overwrite the rest of s.\nfunc window(s []int) []int {\n\treturn s[1:3]\n}\n\nfunc main() {}"}},"title":"Two slices, one array"},{"conceptTags":["concurrency.mutex"],"explanation":"A goroutine does not make its arguments private. If two workers share a slice, you must reason about the slice descriptor and the array it refers to. Making extra goroutines can expose an ownership mistake that a sequential example concealed.","id":"collections.concurrent-slices","objective":"Separate shared headers, shared elements and safe collection of concurrent results.","task":{"reading":{}},"title":"Shared slices and concurrent append"},{"conceptTags":["maps.zero-value"],"explanation":"Reading a key that is absent returns the value type's zero value, with no error. That is why comma-ok exists: v, ok := m[k] distinguishes \"absent\" from \"present and zero\".\n\nThe asymmetry to remember: reading from a nil map is legal and returns zero values, but writing to one panics. A map must be made before it can be written.","id":"collections.map-zero-value","idiomaticSolution":"func countWords(words []string) map[string]int {\n\tcounts := make(map[string]int, len(words))\n\tfor _, word := range words {\n\t\tcounts[word]++\n\t}\n\treturn counts\n}","objective":"Use comma-ok, and know which map operation panics.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestCountWords(t *testing.T) {\n\tgot := countWords([]string{\"go\", \"go\", \"forge\"})\n\tif got[\"go\"] != 2 || got[\"forge\"] != 1 {\n\t\tt.Errorf(\"counts = %v\", got)\n\t}\n\tif got[\"absent\"] != 0 {\n\t\tt.Errorf(\"missing key returned %d, want 0\", got[\"absent\"])\n\t}\n}","starter":"package main\n\n// countWords returns how many times each word appears.\nfunc countWords(words []string) map[string]int {\n\tvar counts map[string]int\n\tfor _, word := range words {\n\t\tcounts[word]++\n\t}\n\treturn counts\n}\n\nfunc main() {}"}},"title":"Reading a missing key is fine, writing to a nil map is not"},{"conceptTags":["strings.runes"],"explanation":"A Go string is an immutable sequence of bytes, commonly containing UTF-8. `s[i]` returns one byte and `len(s)` counts bytes.\n\nRanging over a string decodes UTF-8 and yields each rune with its byte offset. A rune is a Unicode code point, not necessarily a whole displayed character: combining marks and emoji sequences can contain several code points.","id":"collections.runes-not-bytes","objective":"Index, slice and iterate a string without corrupting characters.","task":{"predict":{"answer":"6 5, then 0:h 1:é.\n\né is two bytes in UTF-8, so the byte length is one more than the rune count, and the offset after é jumps from 1 to 3.","question":"Why do the two lengths differ, and which byte offsets appear?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := \"héllo\"\n\tfmt.Println(len(s), len([]rune(s)))\n\tfor i, r := range s {\n\t\tif i < 3 {\n\t\t\tfmt.Printf(\"%d:%c \", i, r)\n\t\t}\n\t}\n\tfmt.Println()\n}"}},"title":"A string is bytes; range gives you runes"},{"conceptTags":["range-over-func"],"explanation":"Since Go 1.23, `range` accepts a function as well as a slice, map or channel. A function of the shape `func(yield func(V) bool)` is an iterator: it calls `yield` once per element, and stops early when `yield` returns false — which is how a `break` in the caller's loop reaches you.\n\nThe language accepts functions that yield zero, one or two values. The standard library names the two value-producing shapes in `iter`: `iter.Seq[V]` yields one value per step, and `iter.Seq2[K, V]` yields two, which is what map-like iteration needs. The zero-value shape is `func(yield func() bool)` and is used with `for range sequence`. These are three language signatures, not three named types in `iter`.\n\nAfter `yield` returns false, return without calling it again. Do not save yield for later or invoke it from another goroutine. A sequence may own resources, so its early-exit path must release them as well.\n\nThe point is not novelty. Before this, a function returning a sequence had to hand back a whole slice — allocating every element even when the caller wanted the first one — or take a callback and lose `break`, `continue` and `return`. An iterator is lazy and keeps the loop keywords working, which is why `slices.Values` and `maps.Keys` return one instead of a copy.","id":"collections.iterators","idiomaticSolution":"// iter.Seq[string], spelled out. Writing the signature rather than\n// importing iter keeps the shape visible: one yield, one bool back.\nfunc Take(values []string, n int) func(func(string) bool) {\n\treturn func(yield func(string) bool) {\n\t\tfor i, value := range values {\n\t\t\tif i >= n {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// False means the caller broke out. Returning here is what\n\t\t\t// makes break, continue and return work in their loop.\n\t\t\tif !yield(value) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}","objective":"Write something that can be ranged over without building a slice first.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc collect(seq func(func(string) bool)) []string {\n\tvar out []string\n\tfor v := range seq {\n\t\tout = append(out, v)\n\t}\n\treturn out\n}\n\nfunc TestTakeStopsAtN(t *testing.T) {\n\tgot := collect(Take([]string{\"a\", \"b\", \"c\", \"d\"}, 2))\n\tif len(got) != 2 || got[0] != \"a\" || got[1] != \"b\" {\n\t\tt.Fatalf(\"Take(4 values, 2) = %v, want [a b]\", got)\n\t}\n}\n\nfunc TestTakeAllowsFewerThanN(t *testing.T) {\n\tif got := collect(Take([]string{\"a\"}, 5)); len(got) != 1 {\n\t\tt.Errorf(\"Take(1 value, 5) = %v, want one value\", got)\n\t}\n}\n\n// Breaking out of the caller's loop makes yield return false, and\n// an iterator that ignores that keeps working after nobody reads.\nfunc TestBreakingOutStopsTheIterator(t *testing.T) {\n\tvisited := 0\n\tfor range Take([]string{\"a\", \"b\", \"c\"}, 3) {\n\t\tvisited++\n\t\tbreak\n\t}\n\tif visited != 1 {\n\t\tt.Errorf(\"the loop body ran %d times after a break, want 1\", visited)\n\t}\n}\n\nfunc TestTakeNoneYieldsNothing(t *testing.T) {\n\tif got := collect(Take([]string{\"a\", \"b\"}, 0)); len(got) != 0 {\n\t\tt.Errorf(\"Take(2 values, 0) = %v, want nothing\", got)\n\t}\n}","starter":"package main\n\n// Take should return an iterator over at most n values from the\n// slice — nothing copied up front, and a caller that breaks out\n// early must stop the work rather than run to the end.\n\nfunc main() {\n\tfor value := range Take([]string{\"go\", \"forge\", \"run\"}, 2) {\n\t\tprintln(value)\n\t}\n}"}},"title":"range works on functions too"},{"conceptTags":["slices.bounds","slices.capacity"],"explanation":"A slice has both a length and a capacity, and they gate different things. Indexing is checked against len: `s[i]` panics the moment i reaches len, however much capacity remains behind it. Reslicing is checked against cap: `s[:n]` is legal for any n up to cap, and that is how a slice grows back into space it had already allocated.\n\nThis is why `make([]int, 0, 10)` is not indexable at all and `make([]int, 10)` is: the first has room for ten and holds none.","id":"collections.bounds","objective":"Say which of two similar-looking index expressions panics.","task":{"predict":{"answer":"3 8\n6 8\npanic on index","question":"What does this print?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\ts := make([]int, 3, 8)\n\tfmt.Println(len(s), cap(s))\n\n\tgrown := s[:6]\n\tfmt.Println(len(grown), cap(grown))\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"panic on index\")\n\t\t}\n\t}()\n\tfmt.Println(s[5])\n}"}},"title":"len is what you may read; cap is what you may reslice"},{"conceptTags":["runtime.allocation"],"explanation":"Visible length is not retained memory size. A small view can keep an entire allocation reachable. This is often noticed when a parser, cache or queue stores a few bytes from each large input and memory grows far beyond the stored lengths.","id":"collections.retained-buffers","objective":"Recognize retained backing arrays and detach small long-lived results deliberately.","task":{"reading":{}},"title":"A tiny slice can keep a large buffer alive"},{"conceptTags":["maps.order"],"explanation":"The language does not specify map iteration order, and the order may change from one iteration to the next. A small example that repeatedly uses one order does not establish a guarantee.\n\nWhen output must be deterministic, collect the keys, sort them and read values in that sorted order. When order is irrelevant, test the entries without requiring a particular traversal sequence.","id":"collections.map-order","idiomaticSolution":"func SortedKeys(m map[string]int) []string {\n\tkeys := make([]string, 0, len(m))\n\tfor key := range m {\n\t\tkeys = append(keys, key)\n\t}\n\tslices.Sort(keys)\n\treturn keys\n}","objective":"Produce stable output from a map without hoping.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestSortedKeys(t *testing.T) {\n\tgot := SortedKeys(map[string]int{\"c\": 1, \"a\": 2, \"b\": 3})\n\twant := []string{\"a\", \"b\", \"c\"}\n\n\tif len(got) != len(want) {\n\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t}\n\tfor i := range want {\n\t\tif got[i] != want[i] {\n\t\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t\t}\n\t}\n\tif SortedKeys(nil) != nil && len(SortedKeys(nil)) != 0 {\n\t\tt.Error(\"an empty map should give an empty result\")\n\t}\n}","starter":"package main\n\n// SortedKeys returns the map's keys in ascending order.\nfunc SortedKeys(m map[string]int) []string {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"Map iteration order is not specified"},{"conceptTags":["strings.builder"],"explanation":"Strings are immutable. Repeated `s += piece` operations in a growing loop can copy the accumulated prefix repeatedly, producing quadratic work as the output grows. Small fixed concatenations may be optimized differently, so measure the actual workload.\n\n`strings.Builder` accumulates text in a growing buffer and exposes the result with `String`. `strings.Join` is a simpler choice when all pieces are already collected. A non-zero Builder must not be copied.","id":"collections.strings-builder","idiomaticSolution":"func Repeat(word string, n int) string {\n\tvar b strings.Builder\n\tfor i := 0; i < n; i++ {\n\t\tif i > 0 {\n\t\t\tb.WriteByte(' ')\n\t\t}\n\t\tb.WriteString(word)\n\t}\n\treturn b.String()\n}","objective":"Use strings.Builder for repeated construction without rebuilding the prefix.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestRepeat(t *testing.T) {\n\tif got := Repeat(\"go\", 3); got != \"go go go\" {\n\t\tt.Errorf(\"Repeat = %q, want %q\", got, \"go go go\")\n\t}\n\tif got := Repeat(\"go\", 1); got != \"go\" {\n\t\tt.Errorf(\"Repeat = %q, want %q\", got, \"go\")\n\t}\n\tif got := Repeat(\"go\", 0); got != \"\" {\n\t\tt.Errorf(\"Repeat = %q, want empty\", got)\n\t}\n}","starter":"package main\n\n// Repeat joins n copies of word with a single space between them.\n// Build it without concatenating in the loop.\nfunc Repeat(word string, n int) string {\n\tout := \"\"\n\tfor i := 0; i < n; i++ {\n\t\tout += word + \" \"\n\t}\n\treturn out\n}\n\nfunc main() {}"}},"title":"Concatenating in a loop repeatedly rebuilds a string"},{"conceptTags":["builtin.make-new","maps.zero-value"],"explanation":"The Tour's \"Creating a slice with make\" page and Effective Go's \"Allocation with new\" page are the same distinction. `new(T)` allocates a zero T and returns `*T`. Since Go 1.26, `new(expr)` can instead initialize the new variable with an expression: `new(42)` returns `*int` pointing at 42. This does not initialize a nil map when the operand is the map type. `make` is only for slices, maps and channels: it returns an initialized value, not a pointer to one.\n\n`new(map[string]int)` is a pointer to a nil map. Writing through it panics. `make(map[string]int)` is a map you can write. The same trap exists for a slice: `new([]int)` is `*[]int` pointing at nil; `make([]int, 0, 8)` is a slice with room. `new(make(map[string]int))` is a pointer to an initialized map, but prefer the map value itself unless pointer-to-map semantics are specifically needed. Older language versions reject the expression form of `new`.","id":"collections.make-and-new","idiomaticSolution":"func ReadyMap() map[string]int { return make(map[string]int) }\nfunc ZeroCounter() *int        { return new(int) }","objective":"Pick make or new for a slice, a map and a pointer.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestReadyMapIsWritable(t *testing.T) {\n\tm := ReadyMap()\n\tif m == nil {\n\t\tt.Fatal(\"ReadyMap returned nil; use make, not new\")\n\t}\n\tm[\"hits\"]++\n\tif m[\"hits\"] != 1 {\n\t\tt.Fatalf(\"hits = %d, want 1\", m[\"hits\"])\n\t}\n}\n\nfunc TestZeroCounterPointsAtZero(t *testing.T) {\n\tp := ZeroCounter()\n\tif p == nil {\n\t\tt.Fatal(\"ZeroCounter returned nil\")\n\t}\n\tif *p != 0 {\n\t\tt.Fatalf(\"*p = %d, want 0\", *p)\n\t}\n\t*p = 4\n\tif *p != 4 {\n\t\tt.Fatalf(\"the pointer should be writable, *p = %d\", *p)\n\t}\n}","starter":"package main\n\n// ReadyMap must be writable. ZeroCounter must be a pointer to 0,\n// not a nil *int.\nfunc ReadyMap() map[string]int { return nil }\nfunc ZeroCounter() *int        { return nil }\n\nfunc main() {}"}},"title":"make initializes collections; new returns a pointer"},{"conceptTags":["types.array","slices.capacity"],"explanation":"The Tour's \"Arrays\" page is the one people skip because slices are what you use. Then a function signature says `[32]byte` and the compiler refuses a `[16]byte`. The length is in the type: `[4]int` and `[3]int` are as different as `int` and `string`.\n\nAn array is a value. Assigning it copies every element. A slice is a header pointing at an array, which is why two slices can share memory and two arrays never do unless you pass a pointer. The conversion is one way and explicit: `s := a[:]` views the array; there is no implicit `[n]T` from a slice of the wrong length.","id":"collections.arrays","idiomaticSolution":"func FirstThree(values [4]int) [3]int {\n\treturn [3]int{values[0], values[1], values[2]}\n}","objective":"Write a function that takes [4]int and returns [3]int.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestFirstThree(t *testing.T) {\n\tgot := FirstThree([4]int{9, 8, 7, 6})\n\twant := [3]int{9, 8, 7}\n\tif got != want {\n\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t}\n}","starter":"package main\n\n// FirstThree returns the first three elements as an array, not\n// a slice. The length has to be in the type.\nfunc FirstThree(values [4]int) [3]int {\n\treturn [3]int{}\n}\n\nfunc main() {}"}},"title":"The length is part of an array's type"},{"conceptTags":["maps.comma-ok","maps.zero-value"],"explanation":"The Tour's \"Mutating Maps\" page is the two-value read: `elem, ok := m[key]`. A missing key and a present zero look the same if you only take `elem`. Scores, counts, flags — anything whose zero is a legitimate stored value — need the ok.\n\n`delete(m, key)` is the other half of that page. Deleting a missing key is a no-op, not an error. After delete, ok is false even if the old value was zero.","id":"collections.map-ok","idiomaticSolution":"func Has(m map[string]int, key string) bool {\n\t_, ok := m[key]\n\treturn ok\n}","objective":"Report whether a key is present when its value can be zero.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestHasTellsZeroFromMissing(t *testing.T) {\n\tm := map[string]int{\"zero\": 0, \"one\": 1}\n\tif !Has(m, \"zero\") {\n\t\tt.Error(\"a stored zero is present\")\n\t}\n\tif !Has(m, \"one\") {\n\t\tt.Error(\"one should be present\")\n\t}\n\tif Has(m, \"nope\") {\n\t\tt.Error(\"a missing key is not present\")\n\t}\n}","starter":"package main\n\n// Has reports whether key is in m, even when m[key] is 0.\nfunc Has(m map[string]int, key string) bool {\n\treturn m[key] != 0\n}\n\nfunc main() {}"}},"title":"Comma-ok is how you tell zero from missing"},{"conceptTags":["slices.capacity"],"explanation":"The Tour's \"Nil slices\" page: the zero value of a slice is nil, it has length and capacity 0, and it has no backing array. `append` treats that as a valid empty slice and allocates. JSON encodes a nil slice as `null` and a non-nil empty one as `[]` — the only common place the distinction leaks out.\n\n`s == nil` is true for `var s []int` and false for `s := []int{}`. Both have len 0. Prefer `len(s) == 0` unless you are talking to a wire format that cares.","id":"collections.nil-slice","objective":"Predict what len, == nil and append do to a zero slice.","task":{"predict":{"answer":"true 0 0\nfalse 1 1\nfalse 0","question":"What does this print?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar s []int\n\tfmt.Println(s == nil, len(s), cap(s))\n\ts = append(s, 1)\n\tfmt.Println(s == nil, len(s), s[0])\n\tempty := []int{}\n\tfmt.Println(empty == nil, len(empty))\n}"}},"title":"A nil slice is empty, and append still works"},{"conceptTags":["functions.value","functions.closure"],"explanation":"The Tour's \"Function values\" page: functions are values. They can be arguments and results. The type includes the parameters and the result, so `func(int) int` and `func(int) string` are as different as int and string.\n\nThis is not a method and not a generic yet. It is the shape map and filter had in Go before type parameters, and it is still how most callbacks are written.","id":"collections.function-values","idiomaticSolution":"func Apply(values []int, fn func(int) int) []int {\n\tout := make([]int, len(values))\n\tfor i, v := range values {\n\t\tout[i] = fn(v)\n\t}\n\treturn out\n}","objective":"Apply a func(int) int to every element of a slice.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestApply(t *testing.T) {\n\tgot := Apply([]int{1, 2, 3}, func(n int) int { return n * n })\n\tif len(got) != 3 || got[0] != 1 || got[2] != 9 {\n\t\tt.Fatalf(\"got %v, want [1 4 9]\", got)\n\t}\n\tif len(Apply(nil, func(n int) int { return n })) != 0 {\n\t\tt.Fatal(\"empty in, empty out\")\n\t}\n}","starter":"package main\n\n// Apply returns fn(v) for each v, in order.\nfunc Apply(values []int, fn func(int) int) []int {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"A function is a value you can pass"}],"summary":"Length against capacity, shared backing arrays, and why a string is not a []char.","title":"Slices, maps and strings","translationNote":"This is where habits from Python and JavaScript do real damage. A Go slice is a view over an array, not a list object, so two slices can share memory and a third can silently observe your writes."},{"id":"interfaces","lessons":[{"conceptTags":["interfaces.size"],"explanation":"A type satisfies an interface by having the methods. There is no implements keyword and no import relationship, so a package can accept types that were written before its interface existed.\n\nThe idiom that follows: accept interfaces, return structs. And keep the interface as small as the function actually uses — one method is common and two is already a design decision.","id":"interfaces.implicit","idiomaticSolution":"type sized interface {\n\tLen() int\n}\n\nfunc summarise(s sized) int {\n\treturn s.Len()\n}","objective":"Write the smallest interface a function needs, at the call site.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\ntype fakeSized struct{ n int }\n\nfunc (f fakeSized) Len() int { return f.n }\n\nfunc TestSummariseAcceptsAnySized(t *testing.T) {\n\tif got := summarise(fakeSized{n: 7}); got != 7 {\n\t\tt.Errorf(\"summarise = %d, want 7\", got)\n\t}\n}","starter":"package main\n\nimport \"strings\"\n\n// summarise should accept anything that can report its own length,\n// not just a strings.Builder.\nfunc summarise(b *strings.Builder) int {\n\treturn b.Len()\n}\n\nfunc main() {}"}},"title":"The consumer declares the interface"},{"conceptTags":["interfaces.method-set"],"explanation":"A method with a value receiver belongs to both T and *T. A method with a pointer receiver belongs only to *T.\n\nSo if any method that satisfies an interface has a pointer receiver, a plain value does not satisfy it — and the compiler says \"does not implement\", often pointing at a line that looks obviously correct. The fix is nearly always &value rather than changing the receiver.","id":"interfaces.method-sets","objective":"Predict whether a value or only a pointer satisfies an interface.","task":{"predict":{"answer":"1.\n\nAdd has a pointer receiver, so it is in the method set of *Counter only. `var a adder = c` would not compile.","question":"Why must the assignment use &c, and what does this print?","source":"package main\n\nimport \"fmt\"\n\ntype Counter struct{ n int }\n\nfunc (c *Counter) Add()      { c.n++ }\nfunc (c Counter) Total() int { return c.n }\n\ntype adder interface{ Add() }\n\nfunc main() {\n\tvar c Counter\n\tvar a adder = &c\n\ta.Add()\n\tfmt.Println(c.Total())\n}"}},"title":"Pointer receiver, pointer method set"},{"conceptTags":["interfaces.nil"],"explanation":"An interface value holds a dynamic type and a dynamic value. It is nil only when it holds neither. Assigning a nil `*MyError` to an `error` variable preserves the pointer type, so `err != nil` is true even though its contained pointer is nil.\n\nWhen a function returns an error interface, return literal `nil` on the success path rather than a typed nil pointer. Calling a method on an interface holding a nil pointer is safe only if that method deliberately supports a nil receiver.","id":"interfaces.nil","idiomaticSolution":"func check(name string) error {\n\tif err := find(name); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}","objective":"Explain why err != nil can be true when the error is nil.","task":{"predict":{"answer":"false.\n\ncheck returns an error interface holding type *PathError with a nil value, and an interface is nil only when its type is nil too. Returning nil explicitly on the success path fixes it.","question":"Does this print true or false, and why?","source":"package main\n\nimport \"fmt\"\n\ntype PathError struct{ Path string }\n\nfunc (e *PathError) Error() string { return \"bad path: \" + e.Path }\n\nfunc find(name string) *PathError { return nil }\n\nfunc check(name string) error { return find(name) }\n\nfunc main() {\n\tfmt.Println(check(\"ok\") == nil)\n}"}},"title":"A nil pointer in an interface is not a nil interface"},{"conceptTags":["types.assertion"],"explanation":"A type assertion has two forms and the difference matters. `v := x.(int)` panics when x is not an int. `v, ok := x.(int)` never panics: ok says whether it worked, and v is the zero value when it did not. In anything that handles input you did not write, the two-value form is the only one.\n\nA type switch is the same question asked about several types at once, and it is how Go writes what other languages do with pattern matching or a visitor.","id":"interfaces.type-switch","idiomaticSolution":"func Describe(value any) string {\n\tswitch v := value.(type) {\n\tcase int:\n\t\treturn fmt.Sprintf(\"int %d\", v)\n\tcase string:\n\t\treturn fmt.Sprintf(\"string %s\", v)\n\tcase bool:\n\t\treturn fmt.Sprintf(\"bool %t\", v)\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}","objective":"Read a value out of an interface without risking a panic.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestDescribe(t *testing.T) {\n\tfor _, c := range []struct {\n\t\tin   any\n\t\twant string\n\t}{\n\t\t{7, \"int 7\"},\n\t\t{\"go\", \"string go\"},\n\t\t{true, \"bool true\"},\n\t\t{1.5, \"unknown\"},\n\t\t{nil, \"unknown\"},\n\t} {\n\t\tif got := Describe(c.in); got != c.want {\n\t\t\tt.Errorf(\"Describe(%v) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}","starter":"package main\n\nimport \"fmt\"\n\n// Describe returns \"int 7\", \"string go\", \"bool true\" or\n// \"unknown\" for anything else. Use a type switch.\nfunc Describe(value any) string {\n\treturn \"\"\n}\n\nfunc main() { fmt.Println(Describe(7)) }"}},"title":"Asking an interface what it is holding"},{"conceptTags":["types.embedding","interfaces.method-set"],"explanation":"Writing a type inside a struct without a field name embeds it, and its methods are promoted to the outer type. It looks like inheritance and is not: there is no virtual dispatch and no super. The outer type gets a field it can reach through, and the promoted methods still run against that inner value.\n\nThe consequence people trip on: a method the outer type declares shadows the promoted one for outside callers, but a promoted method calling a sibling still calls the inner one. Go resolves this at compile time by name, not at run time by receiver.","id":"interfaces.embedding","objective":"Predict which method runs when an embedded type has one too.","task":{"predict":{"answer":"LOUD ada\nhello from base ada","question":"What does this print? Look carefully at the second line.","source":"package main\n\nimport \"fmt\"\n\ntype Base struct{ Name string }\n\nfunc (b Base) Describe() string { return \"base \" + b.Name }\nfunc (b Base) Greet() string    { return \"hello from \" + b.Describe() }\n\ntype Loud struct{ Base }\n\nfunc (l Loud) Describe() string { return \"LOUD \" + l.Name }\n\nfunc main() {\n\tl := Loud{Base{Name: \"ada\"}}\n\tfmt.Println(l.Describe())\n\tfmt.Println(l.Greet())\n}"}},"title":"Embedding is not inheritance"},{"conceptTags":["fmt.stringer","interfaces.size"],"explanation":"`fmt.Stringer` is a small formatting contract:\n\n```go\ntype Stringer interface { String() string }\n```\n\nCommon string formatting operations in `fmt` call `String()` when the value implements it. Format verbs that explicitly request another representation may behave differently. No registration is needed.\n\nDo not format the same value through its own String method in a way that calls String again. Convert it to its underlying type or format its fields to avoid recursion.","id":"interfaces.stringer","idiomaticSolution":"func (ip IPAddr) String() string {\n\treturn fmt.Sprintf(\"%d.%d.%d.%d\", ip[0], ip[1], ip[2], ip[3])\n}","objective":"Make a type print itself as a dotted IPv4 address.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestIPAddrStringer(t *testing.T) {\n\tgot := fmt.Sprint(IPAddr{1, 2, 3, 4})\n\tif got != \"1.2.3.4\" {\n\t\tt.Fatalf(\"Sprint = %q, want 1.2.3.4\", got)\n\t}\n\tif (IPAddr{127, 0, 0, 1}).String() != \"127.0.0.1\" {\n\t\tt.Fatal(\"localhost should print 127.0.0.1\")\n\t}\n}","starter":"package main\n\ntype IPAddr [4]byte\n\n// String should print 1.2.3.4 for IPAddr{1, 2, 3, 4}.\nfunc (ip IPAddr) String() string {\n\treturn \"\"\n}\n\nfunc main() {}"}},"title":"fmt looks for String(), not a Stringer keyword"},{"conceptTags":["interfaces.empty","types.assertion"],"explanation":"The Tour's \"The empty interface\" page: `interface{}` specifies zero methods, so every type implements it. `any` is the alias. `fmt.Print` takes `...any` for that reason.\n\nHolding a value in `any` throws the static type away. Getting it back is a type assertion or a type switch — the two-value form, or you panic. `%T` in fmt is the cheap way to see what is inside, and it is what this lesson asks you to return.","id":"interfaces.empty","idiomaticSolution":"func Kind(value any) string {\n\treturn fmt.Sprintf(\"%T\", value)\n}","objective":"Report the dynamic type of a value held in any.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestKind(t *testing.T) {\n\tn := 3\n\tfor _, c := range []struct {\n\t\tin   any\n\t\twant string\n\t}{\n\t\t{7, \"int\"},\n\t\t{\"go\", \"string\"},\n\t\t{true, \"bool\"},\n\t\t{&n, \"*int\"},\n\t\t{nil, \"<nil>\"},\n\t} {\n\t\tif got := Kind(c.in); got != c.want {\n\t\t\tt.Errorf(\"Kind(%v) = %q, want %q\", c.in, got, c.want)\n\t\t}\n\t}\n}","starter":"package main\n\n// Kind returns the dynamic type, as fmt would: \"int\", \"string\",\n// \"*int\". A nil any prints as <nil>.\nfunc Kind(value any) string {\n\treturn \"\"\n}\n\nfunc main() {}"}},"title":"any is interface{}, and it has no methods"}],"summary":"Implicit satisfaction, method sets, and the nil that is not nil.","title":"Interfaces","translationNote":"Nothing declares that it implements an interface. That inverts where abstraction lives: the consumer defines the interface it needs, so the useful interfaces are small and defined next to the code using them, not next to the type satisfying them."},{"id":"generics","lessons":[{"conceptTags":["generics.type-parameter"],"explanation":"Type parameters go in square brackets before the ordinary ones: `func Map[T, U any](in []T, f func(T) U) []U`. `T` and `U` are types the caller supplies, and in almost every call the compiler infers them so you write `Map(names, length)` with no brackets at all.\n\n`any` is the constraint that allows every type. It is a real alias for `interface{}`, but in this position it means something different: with `interface{}` as a *parameter* type you get a value you must assert your way out of, and with `any` as a *constraint* you get the caller's actual type, checked at compile time.\n\nThat is the whole gain. The old version of this function returned `[]interface{}` and every caller unpacked it; the generic one returns `[]U`, and a mistake is a compile error rather than a panic.","id":"generics.type-parameters","idiomaticSolution":"func Keep[T any](in []T, keep func(T) bool) []T {\n\tvar out []T\n\tfor _, value := range in {\n\t\tif keep(value) {\n\t\t\tout = append(out, value)\n\t\t}\n\t}\n\treturn out\n}","objective":"Write a function that works for several types without interface{} and without a cast.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestKeepOnInts(t *testing.T) {\n\tgot := Keep([]int{1, 2, 3, 4, 5}, func(n int) bool { return n%2 == 1 })\n\twant := []int{1, 3, 5}\n\tif len(got) != len(want) {\n\t\tt.Fatalf(\"Keep returned %v, want %v\", got, want)\n\t}\n\tfor i := range want {\n\t\tif got[i] != want[i] {\n\t\t\tt.Fatalf(\"Keep returned %v, want %v\", got, want)\n\t\t}\n\t}\n}\n\n// The point of the type parameter: this must compile, and the\n// result must already be []string with nothing to assert.\nfunc TestKeepOnStrings(t *testing.T) {\n\tgot := Keep([]string{\"go\", \"\", \"forge\"}, func(s string) bool { return s != \"\" })\n\tif len(got) != 2 || got[0] != \"go\" || got[1] != \"forge\" {\n\t\tt.Fatalf(\"Keep returned %v\", got)\n\t}\n}\n\nfunc TestKeepOnEmpty(t *testing.T) {\n\tif got := Keep([]int{}, func(int) bool { return true }); len(got) != 0 {\n\t\tt.Errorf(\"Keep on an empty slice returned %v\", got)\n\t}\n}","starter":"package main\n\n// Keep should return a new slice holding the elements the predicate\n// returns true for, for any element type — no interface{} anywhere,\n// and the result keeps the caller's type.\n\nfunc main() {\n\teven := Keep([]int{1, 2, 3, 4}, func(n int) bool { return n%2 == 0 })\n\tprintln(len(even))\n}"}},"title":"A type parameter is written in square brackets"},{"conceptTags":["generics.constraint"],"explanation":"A constraint says what the compiler may assume about `T`. It is written as an interface — the same keyword — but an interface used as a constraint can list *types* as well as methods:\n\n```\ntype Number interface {\n\t~int | ~int64 | ~float64\n}\n```\n\nThe `|` is a union, and the `~` means \"any type whose underlying type is this\", so `type Celsius float64` satisfies `~float64`. Without the tilde your own named types are excluded, which is almost never what you meant.\n\nThe standard library provides `cmp.Ordered` for types that support ordering. `constraints` is not a standard-library package. Reaching for `cmp.Ordered` before writing your own is useful, because a constraint is part of your API and a homemade one is a second vocabulary for readers to learn.","id":"generics.constraints","idiomaticSolution":"// The tilde is what lets a named type through: Celsius has float64 as\n// its underlying type, and without ~ it would be rejected.\ntype Number interface {\n\t~int | ~int8 | ~int16 | ~int32 | ~int64 |\n\t~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |\n\t~float32 | ~float64 | ~complex64 | ~complex128\n}\n\nfunc Sum[T Number](values []T) T {\n\tvar total T\n\tfor _, value := range values {\n\t\ttotal += value\n\t}\n\treturn total\n}","objective":"Constrain a type parameter to what your code actually needs.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\ntype Celsius float64\n\nfunc TestSumInts(t *testing.T) {\n\tif got := Sum([]int{1, 2, 3, 4}); got != 10 {\n\t\tt.Errorf(\"Sum ints = %d, want 10\", got)\n\t}\n}\n\nfunc TestSumFloats(t *testing.T) {\n\tif got := Sum([]float64{1.5, 2.5}); got != 4 {\n\t\tt.Errorf(\"Sum floats = %v, want 4\", got)\n\t}\n}\n\n// A named type with a numeric underlying type. This is what the\n// tilde is for; without it this does not compile.\nfunc TestSumNamedType(t *testing.T) {\n\tif got := Sum([]Celsius{10, 12}); got != 22 {\n\t\tt.Errorf(\"Sum named = %v, want 22\", got)\n\t}\n}\n\nfunc TestSumEmptyIsZero(t *testing.T) {\n\tif got := Sum([]int{}); got != 0 {\n\t\tt.Errorf(\"Sum of nothing = %d, want 0\", got)\n\t}\n}\n\nfunc TestSumSupportsNumericFamilies(t *testing.T) {\n\tif Sum([]uint64{1, 2}) != 3 { t.Fatal(\"unsigned sum\") }\n\tif Sum([]int8{-2, 3}) != 1 { t.Fatal(\"small signed sum\") }\n\tif Sum([]complex128{1+2i, 3-1i}) != 4+1i { t.Fatal(\"complex sum\") }\n}","starter":"package main\n\n// Sum should add up a slice of any numeric type and return the same\n// type it was given. Define whatever constraint it needs.\n\nfunc main() {\n\tprintln(Sum([]int{1, 2, 3}))\n}"}},"title":"A constraint is an interface with types in it"},{"conceptTags":["generics.type-parameter"],"explanation":"Types take parameters with the same syntax: `type Stack[T any] struct { items []T }`. Methods on it repeat the parameter in the receiver — `func (s *Stack[T]) Push(v T)` — which makes the type's parameter available to the method.\n\nFor most of generics' life a method could not introduce a parameter of its own, so transformations to another type were written as functions before Go 1.27. That restriction is gone; the next lesson is about what replaced it.\n\nThe zero value still has to work. `var s Stack[int]` gives you a struct whose slice is nil, and appending to a nil slice is fine, so the stack is usable without a constructor — worth designing for rather than stumbling into.\n\nPopping must also clear the obsolete array slot before shortening the slice. Otherwise a stack of pointers, slices or interfaces can keep removed objects reachable while its backing array stays alive. The returned value remains valid; clearing the slot releases only the container's extra reference.\n\nInstantiation is explicit where inference has nothing to work from: `Stack[int]{}` names the type, while `Push(1)` infers nothing because `T` is already fixed by the receiver.","id":"generics.containers","idiomaticSolution":"type Stack[T any] struct {\n\titems []T\n}\n\nfunc (s *Stack[T]) Push(value T) {\n\t// A nil slice appends fine, which is what makes the zero value work.\n\ts.items = append(s.items, value)\n}\n\nfunc (s *Stack[T]) Pop() (T, bool) {\n\tif len(s.items) == 0 {\n\t\t// The zero value of T, whatever T turned out to be.\n\t\tvar zero T\n\t\treturn zero, false\n\t}\n\tlast := len(s.items) - 1\n\tvalue := s.items[last]\n\tvar zero T\n\ts.items[last] = zero\n\ts.items = s.items[:last]\n\treturn value, true\n}","objective":"Write a container that holds one type rather than any type.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestStackIsLastInFirstOut(t *testing.T) {\n\tvar s Stack[int]\n\ts.Push(1)\n\ts.Push(2)\n\n\tif value, ok := s.Pop(); !ok || value != 2 {\n\t\tt.Fatalf(\"first Pop = %d, %v; want 2, true\", value, ok)\n\t}\n\tif value, ok := s.Pop(); !ok || value != 1 {\n\t\tt.Fatalf(\"second Pop = %d, %v; want 1, true\", value, ok)\n\t}\n}\n\nfunc TestPoppingAnEmptyStackReportsIt(t *testing.T) {\n\tvar s Stack[string]\n\tvalue, ok := s.Pop()\n\tif ok {\n\t\tt.Errorf(\"Pop on an empty stack said ok, returning %q\", value)\n\t}\n\tif value != \"\" {\n\t\tt.Errorf(\"Pop on an empty stack returned %q, want the zero value\", value)\n\t}\n}\n\nfunc TestTheZeroValueIsUsable(t *testing.T) {\n\tvar s Stack[int]\n\ts.Push(7)\n\tif value, ok := s.Pop(); !ok || value != 7 {\n\t\tt.Errorf(\"a stack used without a constructor lost its value\")\n\t}\n}","starter":"package main\n\n// A Stack that holds one element type. Push adds, Pop returns the\n// most recently added value and whether there was one. The zero\n// value must be usable without a constructor.\n\nfunc main() {\n\tvar s Stack[string]\n\ts.Push(\"go\")\n\tvalue, ok := s.Pop()\n\tprintln(value, ok)\n}"}},"title":"A type can take parameters too"},{"conceptTags":["generic-method"],"explanation":"Go 1.27 lets a method declare type parameters of its own, in addition to the ones its receiver already carries:\n\n```\ntype List[E any] []E\n\nfunc (l List[E]) Apply[F any](f func(E) F) List[F] {\n\t...\n}\n```\n\n`E` comes from the receiver; `F` belongs to the method. Before this, the second one had no place to live, so this transformation was commonly written as a package-level function taking the collection as its first argument. That was not a style choice — the language had no way to write it as a method.\n\nLike a generic function, a generic method is instantiated before it is called, and in ordinary code the compiler infers the type argument from what you pass. The judgement from the previous lessons still applies: this removes a restriction, it does not create an obligation. A method earns a type parameter when the transformation genuinely produces a different element type, and not because it now can have one.","id":"generics.methods","idiomaticSolution":"// E is the receiver's; F is the method's own. Before Go 1.27 the second\n// one had nowhere to go, and this had to be func Map[E, F any](Bag[E]…).\nfunc (b Bag[E]) Map[F any](f func(E) F) Bag[F] {\n\tmapped := make([]F, 0, len(b.items))\n\tfor _, item := range b.items {\n\t\tmapped = append(mapped, f(item))\n\t}\n\treturn Bag[F]{items: mapped}\n}","objective":"Write the method that could only be a function before Go 1.27.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestMapChangesTheElementType(t *testing.T) {\n\tb := Bag[int]{items: []int{1, 2, 3}}\n\tgot := b.Map(func(n int) string {\n\t\tif n%2 == 0 {\n\t\t\treturn \"even\"\n\t\t}\n\t\treturn \"odd\"\n\t})\n\n\twant := []string{\"odd\", \"even\", \"odd\"}\n\tif len(got.items) != len(want) {\n\t\tt.Fatalf(\"Map returned %v, want %v\", got.items, want)\n\t}\n\tfor i := range want {\n\t\tif got.items[i] != want[i] {\n\t\t\tt.Fatalf(\"Map returned %v, want %v\", got.items, want)\n\t\t}\n\t}\n}\n\nfunc TestMapOnAnEmptyBag(t *testing.T) {\n\tb := Bag[string]{}\n\tif got := b.Map(func(s string) int { return len(s) }); len(got.items) != 0 {\n\t\tt.Errorf(\"Map over an empty bag returned %v\", got.items)\n\t}\n}\n\n// The receiver's parameter and the method's are independent: this\n// one keeps the element type and only changes the values.\nfunc TestMapCanKeepTheSameType(t *testing.T) {\n\tb := Bag[int]{items: []int{1, 2}}\n\tgot := b.Map(func(n int) int { return n * 10 })\n\tif len(got.items) != 2 || got.items[0] != 10 || got.items[1] != 20 {\n\t\tt.Errorf(\"Map returned %v, want [10 20]\", got.items)\n\t}\n}","starter":"package main\n\n// Bag holds elements of one type. Give it a Map method that returns\n// a Bag of whatever type the function produces — a method, not a\n// package-level function.\n\ntype Bag[E any] struct {\n\titems []E\n}\n\nfunc main() {\n\tb := Bag[int]{items: []int{1, 2, 3}}\n\tprintln(len(b.Map(func(n int) string { return \"x\" }).items))\n}"}},"title":"A method can take its own type parameter"},{"conceptTags":["generics.overuse"],"explanation":"The Go team's own guidance is narrow. Type parameters are for: functions over slices, maps and channels of any element type; general data structures like trees and stacks; and methods that are identical for several types apart from the type itself.\n\nThe case against everything else is readability. A generic function has to be read twice — once for what it does and once for what its constraint permits — and it cannot use anything the constraint does not promise, which usually makes it *less* capable than the concrete version it replaced.\n\nTwo smells worth naming. If the constraint ends up being an interface with methods and nothing else, an ordinary interface parameter is simpler and does the same thing at the cost of one dynamic dispatch. And if a function has a type parameter used exactly once, in one argument, it is a plain function wearing a costume.","id":"generics.when-not-to","objective":"Recognise the three cases where a type parameter earns its place, and the ones where it does not.","task":{"predict":{"answer":"Both print id-7. Write PrintPlain.\n\nThe constraint here is an interface with a method and nothing else,\nso the type parameter buys nothing: there is no second type\ninvolved, no container to keep typed, and no operator that needs a\nconcrete type. What it costs is a signature that has to be read\ntwice.\n\nThe runtime and compiler may handle dispatch and allocation differently.\nNeither version guarantees a heap allocation or a performance\nadvantage; measure before trading clarity for speculation.","question":"Both compile and print the same thing. Which should you write, and why?","source":"package main\n\nimport \"fmt\"\n\ntype Stringer interface {\n\tString() string\n}\n\n// Two ways to write the same thing.\nfunc PrintGeneric[T Stringer](value T) { fmt.Println(value.String()) }\nfunc PrintPlain(value Stringer)        { fmt.Println(value.String()) }\n\ntype ID int\n\nfunc (i ID) String() string { return fmt.Sprintf(\"id-%d\", i) }\n\nfunc main() {\n\tPrintGeneric(ID(7))\n\tPrintPlain(ID(7))\n}"}},"title":"Most code that could be generic should not be"}],"summary":"Type parameters, constraints, and the times an interface is the better answer.","title":"Generics, and when not to","translationNote":"If you are coming from Java or C#, the shape will look familiar and the culture will not. Go got type parameters late and on purpose, and the community's default is still to reach for them last — a function that works on one concrete type is not a failure waiting to be generalised.\n\nThere is no reflection-based erasure story to learn and no covariance rules to fight. Interfaces describe both ordinary values and type-parameter constraints. A constraint with type terms is not an ordinary value type: use it to bound a type parameter."},{"id":"errors","lessons":[{"conceptTags":["errors.wrapping"],"explanation":"fmt.Errorf with %w produces an error that both reads well and still contains the original. errors.Is and errors.As walk that chain.\n\nTwo conventions make the chain readable: error strings are lowercase and unpunctuated because they get concatenated, and each layer adds only what it uniquely knows — usually the operation and its input.","id":"errors.wrapping","idiomaticSolution":"func parsePort(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"parse port %q: %w\", raw, ErrNotANumber)\n\t}\n\treturn n, nil\n}","objective":"Wrap an error so callers can still match the original.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestParsePortWraps(t *testing.T) {\n\t_, err := parsePort(\"http\")\n\tif !errors.Is(err, ErrNotANumber) {\n\t\tt.Fatalf(\"error %v does not match ErrNotANumber\", err)\n\t}\n\tif !strings.Contains(err.Error(), \"http\") {\n\t\tt.Errorf(\"error %q does not mention the input\", err)\n\t}\n}","starter":"package main\n\nimport (\n\t\"errors\"\n\t\"strconv\"\n)\n\nvar ErrNotANumber = errors.New(\"not a number\")\n\n// parsePort should report which input failed and still let callers\n// match ErrNotANumber.\nfunc parsePort(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, ErrNotANumber\n\t}\n\treturn n, nil\n}\n\nfunc main() {}"}},"title":"%w adds context without hiding the cause"},{"conceptTags":["errors.sentinel","errors.wrapping"],"explanation":"errors.Is asks whether anything in the chain equals a sentinel. errors.As asks whether anything in the chain is a particular type, and gives it to you so you can read its fields.\n\nSentinel when the caller only needs to know which kind of failure it was; typed error when the caller needs a detail, such as which field was invalid.","id":"errors.is-and-as","objective":"Choose between errors.Is and errors.As without trial and error.","task":{"guidedTyping":{"target":"var invalid *ValidationError\nif errors.As(err, &invalid) {\n\treturn invalid.Field\n}"}},"title":"Is compares, As extracts"},{"conceptTags":["errors.defer"],"explanation":"A deferred call runs when the function returns, whichever return it was, and deferred calls run in reverse order. That is what makes acquire-then-defer-release safe against every early return an error check introduces.\n\nThe argument to a deferred call is evaluated immediately; only the call is postponed. This surprises people exactly once.","id":"errors.defer","objective":"Release what you acquired, in the right order, on every path.","task":{"predict":{"answer":"end 3 2 1\n\nEach defer captured its own i by value at the moment it was deferred, and the deferred calls run in reverse order.","question":"In what order do the numbers print?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tfor i := 1; i <= 3; i++ {\n\t\tdefer fmt.Print(i, \" \")\n\t}\n\tfmt.Print(\"end \")\n}"}},"title":"defer runs last in, first out"},{"conceptTags":["errors.custom","errors.wrapping"],"explanation":"`error` is an interface with one method, so anything with `Error() string` is one. That is what makes an error able to carry structured information: a field for the line that failed, the value that was rejected, the operation that was attempted.\n\n`errors.As` is the counterpart to `errors.Is`. Where Is asks \"is this that particular error\", As asks \"is there an error of this type anywhere in the chain, and if so give it to me\" — which is how a caller reads those fields back out after the error has been wrapped.","id":"errors.custom-type","idiomaticSolution":"func (e *ParseError) Error() string {\n\treturn fmt.Sprintf(\"field %q: %s\", e.Field, e.Reason)\n}\n\nfunc Parse(field, value string) error {\n\tif field == \"\" {\n\t\treturn &ParseError{Field: field, Reason: \"name is empty\"}\n\t}\n\treturn nil\n}","objective":"Write an error that carries data the caller can read.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n)\n\nfunc TestParseReportsTheField(t *testing.T) {\n\terr := Parse(\"\", \"x\")\n\tif err == nil {\n\t\tt.Fatal(\"expected an error for an empty field\")\n\t}\n\n\twrapped := fmt.Errorf(\"loading config: %w\", err)\n\tvar parseError *ParseError\n\tif !errors.As(wrapped, &parseError) {\n\t\tt.Fatal(\"errors.As should find a *ParseError through the wrapping\")\n\t}\n\tif parseError.Reason == \"\" {\n\t\tt.Error(\"the error should say why\")\n\t}\n\tif err.Error() == \"\" {\n\t\tt.Error(\"Error() should return something\")\n\t}\n\tif Parse(\"name\", \"ada\") != nil {\n\t\tt.Error(\"a valid field should not be an error\")\n\t}\n}","starter":"package main\n\n// ParseError should report which field failed and why, and\n// satisfy the error interface.\ntype ParseError struct {\n\tField  string\n\tReason string\n}\n\n// Parse returns a *ParseError when field is empty.\nfunc Parse(field, value string) error {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"An error is any type with an Error method"},{"conceptTags":["errors.panic","errors.explicit-check"],"explanation":"A file that will not open is a failure: it is expected, the caller can do something about it, and it is an error value. An index past the end of a slice is a bug: the program's own logic is wrong, and continuing would be worse than stopping. Go draws that line deliberately, and a library that panics on bad input has drawn it in the wrong place.\n\n`recover` exists, and its honest use is narrow: stopping one request from taking down a server, at the boundary, before returning an ordinary error. It is not a catch block, and using it as one hides the bug that caused it.","id":"errors.panic","objective":"Say which of two situations deserves a panic.","task":{"predict":{"answer":"fine\n<nil>\nrecovered: bad state","question":"What does this print? Note that err is a named return.","source":"package main\n\nimport \"fmt\"\n\nfunc safe(work func()) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"recovered: %v\", r)\n\t\t}\n\t}()\n\twork()\n\treturn nil\n}\n\nfunc main() {\n\tfmt.Println(safe(func() { fmt.Println(\"fine\") }))\n\tfmt.Println(safe(func() { panic(\"bad state\") }))\n}"}},"title":"panic is for bugs, not for failures"},{"conceptTags":["errors.panic","functions.named-results"],"explanation":"The Tour shows panic as a value and Effective Go keeps recover for a server boundary: one request, one goroutine, then an ordinary error back to the caller. `recover` only works inside a deferred function. A named result is how that error gets out — a `return nil` after `work()` would overwrite it.\n\nA library that recovers in the middle of a calculation is hiding a bug. A process that recovers at main is pretending the program is still sound. The honest width is one unit of work you can abandon.","id":"errors.recover","idiomaticSolution":"func Guard(work func()) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"panic: %v\", r)\n\t\t}\n\t}()\n\twork()\n\treturn nil\n}","objective":"Turn a panic into an error without swallowing the rest of the program.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestGuard(t *testing.T) {\n\tif err := Guard(func() {}); err != nil {\n\t\tt.Fatalf(\"clean work should be nil, got %v\", err)\n\t}\n\terr := Guard(func() { panic(\"boom\") })\n\tif err == nil {\n\t\tt.Fatal(\"a panic should become an error\")\n\t}\n}","starter":"package main\n\n// Guard runs work and returns an error if it panics. A clean\n// run returns nil. Use recover in a defer.\nfunc Guard(work func()) error {\n\twork()\n\treturn nil\n}\n\nfunc main() {}"}},"title":"recover belongs at the boundary"}],"summary":"Wrapping, errors.Is and errors.As, sentinels, defer and the panic boundary.","title":"Errors","translationNote":"There is no catch. An error is a value you return, and the caller decides. What replaces a stack trace is a chain of wrapped context, built deliberately at each level that knows something the level below did not."},{"id":"modules","lessons":[{"conceptTags":["modules.import-path"],"explanation":"`go.mod` names the module, such as `example.com/forge`. A package in `internal/build` is then imported using `example.com/forge/internal/build`.\n\nThe import path locates the package; its `package` clause determines the default name used in source. The name often matches the last directory component, but does not have to. An import alias can choose another local name.\n\nAn `internal` directory also enforces an import boundary: only code within the tree rooted at its parent may import that package.","id":"modules.import-path","objective":"Predict the import path of any package in a module.","task":{"predict":{"answer":"import \"example.com/forge/internal/build\"\n\nThe importer must have an import path within the example.com/forge tree. A separate module named example.com/forge/client can satisfy that rule; other.example/client cannot. The boundary follows the parent import-path tree, rather than the identity of the module.","question":"How does cmd/forge/main.go import Run, and could a different module do the same?","source":"// go.mod\nmodule example.com/forge\n\ngo 1.24\n\n// internal/build/build.go\npackage build\n\nfunc Run() {}"}},"title":"The import path is the module path plus the directory"},{"conceptTags":["interfaces.size"],"explanation":"An identifier starting with an upper-case letter is visible outside its package; anything else is not. There is no public, private or protected.\n\nBecause the name carries the visibility, renaming is an API change, and Go's naming conventions get unusually strict: no stuttering (build.Runner, not build.BuildRunner), no Get prefix on getters, and short names for short-lived variables.","id":"modules.exported-by-case","objective":"Control visibility without keywords, and name things accordingly.","task":{"guidedTyping":{"target":"// Runner executes one build.\ntype Runner struct {\n\tworkdir string\n}\n\nfunc NewRunner(workdir string) *Runner {\n\treturn &Runner{workdir: workdir}\n}"}},"title":"A capital letter is the access modifier"},{"conceptTags":["stdlib.testing"],"explanation":"A test is a function such as `func TestParse(t *testing.T)` in a file ending `_test.go`. It can use the production package name, or a package name ending `_test` to exercise the exported API from outside the package.\n\nA table-driven test keeps cases in data and the assertion in code. `t.Run` gives each case a separate name in the result stream. No external test framework is required.","id":"modules.tests","idiomaticSolution":"func Clamp(value, low, high int) int {\n\tif value < low {\n\t\treturn low\n\t}\n\tif value > high {\n\t\treturn high\n\t}\n\treturn value\n}","objective":"Write a table-driven test and run it locally.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestClamp(t *testing.T) {\n\tcases := []struct {\n\t\tname                  string\n\t\tvalue, low, high, want int\n\t}{\n\t\t{\"inside\", 5, 0, 10, 5},\n\t\t{\"below\", -3, 0, 10, 0},\n\t\t{\"above\", 42, 0, 10, 10},\n\t}\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\tif got := Clamp(c.value, c.low, c.high); got != c.want {\n\t\t\t\tt.Errorf(\"Clamp(%d) = %d, want %d\", c.value, got, c.want)\n\t\t\t}\n\t\t})\n\t}\n}","starter":"package main\n\n// Clamp returns value limited to the range low..high.\nfunc Clamp(value, low, high int) int {\n\treturn value\n}\n\nfunc main() {}"}},"title":"Tests are a file, not a framework"},{"conceptTags":["modules.import-path"],"explanation":"A package's name becomes the qualifier callers read: `http.Server` is clearer than `http.HTTPServer`. Prefer short, descriptive lowercase names. Singular names are common, but useful standard-library packages such as `strings`, `errors` and `slices` are plural.\n\nAvoid needless repetition between package and exported name. `chart.New` can be clear for a package centered on one chart type; a package with several constructors may need more specific names. Read the whole selector to judge it.","id":"modules.naming","objective":"Name a package and its exported function without repeating yourself.","task":{"predict":{"answer":"GO\ntrue\nb3w4r3","question":"What does this print?","source":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc main() {\n\t// Every one of these reads as package.Identifier at the call site.\n\tfmt.Println(strings.ToUpper(\"go\"))\n\tfmt.Println(strings.HasPrefix(\"gopher\", \"go\"))\n\tr := strings.NewReplacer(\"a\", \"4\", \"e\", \"3\")\n\tfmt.Println(r.Replace(\"beware\"))\n}"}},"title":"The package name is half the API"},{"conceptTags":["packages.init"],"explanation":"A package initializes its variables using their dependency relationships, then runs its init functions in source order as presented to the compiler. Imported packages finish initialization before the importing package. `main` starts after the program's initialization completes.\n\nDo not depend on arbitrary file presentation order for important behavior. Explicit constructors make configuration and recoverable failure handling visible. An init function takes no arguments and returns no result, though it can register a driver or format as a deliberate import side effect.","id":"modules.init","objective":"Predict the order of package variables, init and main.","task":{"predict":{"answer":"var first\nvar second\ninit\nmain first second","question":"In what order do the lines appear?","source":"package main\n\nimport \"fmt\"\n\nvar first = announce(\"first\")\nvar second = announce(\"second\")\n\nfunc announce(name string) string {\n\tfmt.Println(\"var\", name)\n\treturn name\n}\n\nfunc init() {\n\tfmt.Println(\"init\")\n}\n\nfunc main() {\n\tfmt.Println(\"main\", first, second)\n}"}},"title":"init runs before main, and order is defined"},{"conceptTags":["modules.identity-versions"],"explanation":"A repository, a module and a package can be three different boundaries. Trace the module path plus the package subdirectory before changing imports. A version suffix is part of the import identity; a folder name alone does not decide which source the compiler builds.","id":"modules.identity-versions","objective":"Resolve module roots, import paths, internal visibility and major-version suffixes.","task":{"reading":{}},"title":"A module is a release boundary; a package is a directory"},{"conceptTags":["modules.version-graph"],"explanation":"A direct require is not a lock on every transitive dependency. Other requirements can raise the selected version of the same module path. Diagnose the graph first, then test the change that actually enters the build; repeatedly deleting go.sum does not explain an upgrade.","id":"modules.version-graph","objective":"Read minimal version selection and investigate a transitive upgrade without guessing.","task":{"reading":{}},"title":"Explain the selected version before running go get"},{"conceptTags":["modules.checksums-private"],"explanation":"A download failure may come from version discovery, credentials, a proxy, the checksum database or local cache integrity. Treat those as separate layers. A checksum records content identity; it neither proves the code is safe nor decides which version the dependency graph chooses.","id":"modules.checksums-private","objective":"Diagnose downloads without leaking private paths or disabling integrity checks globally.","task":{"reading":{}},"title":"Checksums, proxies and private modules solve different problems"},{"conceptTags":["modules.workspace-replace"],"explanation":"A checkout can pass because go.work supplies a sibling module or replace points to a local directory that no consumer has. That success tests the local composition, not the published module. Keep a second path that exercises the version and files a real downstream user receives.","id":"modules.workspace-replace","objective":"Use go.work and replace for development while checking what an independent consumer builds.","task":{"reading":{}},"title":"A local workspace can hide a broken release"},{"conceptTags":["modules.vendor-embed"],"explanation":"A successful build in your checkout can depend on uncommitted generated files, platform-specific source or an asset missing from the release archive. Reproducibility concerns the whole input set: toolchain, selected modules, build constraints, generated files and embedded data.","id":"modules.vendor-embed","objective":"Check the source and assets that a clean build actually receives.","task":{"reading":{}},"title":"Reproduce the artifact: vendor, build tags and embedded files"},{"conceptTags":["modules.parallel-tests"],"explanation":"A test can pass alone and fail when other packages or subtests run at the same time. Shared database names, environment variables, ports and mutable globals turn isolated test intent into interference. Give every test its own resources, and distinguish a data race from a wider coordination bug.","id":"modules.parallel-tests","objective":"Find races, test caching mistakes and shared integration fixtures before scaling concurrency.","task":{"reading":{}},"title":"Parallel tests must own their mutable resources"},{"conceptTags":["modules.benchmark-load"],"explanation":"An ns/op number describes one workload in one process. A production incident may instead come from pool wait, queue growth, a slow downstream service or allocation pressure. Start with the question you need to answer and preserve the workload and environment alongside the measurement.","id":"modules.benchmark-load","objective":"Measure allocations, concurrency and tail latency without mistaking closed-loop throughput for service capacity.","task":{"reading":{}},"title":"A microbenchmark is not a capacity test"},{"conceptTags":["modules.profiles-contention"],"explanation":"A high-latency request does not necessarily consume much CPU. It may be waiting on a mutex, scheduling, a network response or a connection pool. Capture evidence for the same workload and time window, and choose a profile that can explain the suspected delay.","id":"modules.profiles-contention","objective":"Use pprof and traces to investigate latency under load instead of increasing pools blindly.","task":{"reading":{}},"title":"Profile CPU, allocation and waiting as different bottlenecks"},{"conceptTags":["modules.build-capacity"],"explanation":"A burst of parallel compilation can exhaust memory before the program you are testing even starts. Build-cache misses, many packages, cgo and simultaneous jobs change the working set. Read the exact failing phase instead of assuming every slowdown is a goroutine scheduling issue in application code.","id":"modules.build-capacity","objective":"Separate compiler work, runtime goroutines and caches when CI or a small machine stalls.","task":{"reading":{}},"title":"Build concurrency also has a memory budget"},{"conceptTags":["modules.tools-toolchain"],"explanation":"The binary that formats, generates or analyzes your project is part of the workflow’s input. An unpinned command on PATH can silently change generated output or lint results. Keep the intended tool version and compiler selection explicit without confusing them with the libraries your application imports.","id":"modules.tools-toolchain","objective":"Distinguish application dependencies, development commands and toolchain selection.","task":{"reading":{}},"title":"Pin the compiler and the tools that generate your code"},{"conceptTags":["modules.fuzz-vulnerability"],"explanation":"Normal tests often cover the examples you already understand. Parsers and protocol boundaries also receive truncated, oversized and surprising inputs. Fuzzing explores input behavior, while vulnerability analysis asks whether known vulnerable code is reachable; the two tools answer different questions.","id":"modules.fuzz-vulnerability","objective":"Combine fuzzing, regression seeds and govulncheck without treating one green tool as complete assurance.","task":{"reading":{}},"title":"Test unknown inputs and check reachable vulnerabilities"},{"conceptTags":["modules.startup-ownership"],"explanation":"Imported packages initialize before main, and hidden setup can turn an import into a database connection, network wait or process-wide configuration decision. Make those dependencies visible at the composition root so startup, tests, retries and shutdown share a clear owner.","id":"modules.startup-ownership","objective":"Move fallible setup to an explicit owner and close shared resources after work drains.","task":{"reading":{}},"title":"Package initialization is not a request-time connection factory"}],"summary":"Import paths, go.mod, go test and go vet, without a search engine.","title":"Packages, modules and tooling","translationNote":"Go's survey found professionals repeatedly returning to documentation for core go subcommands. That is not a knowledge gap so much as a model gap: once the module, the import path and the package directory line up in your head, the commands stop needing to be memorised."},{"id":"concurrency","lessons":[{"conceptTags":["concurrency.deadlock","concurrency.select"],"explanation":"A send on an unbuffered channel does not complete until a receiver takes the value, and a receive does not complete until a sender provides one. It is a rendezvous, not a mailbox.\n\nThis is why the classic first Go deadlock is one line long: send on an unbuffered channel from the only goroutine there is, and nobody can ever arrive to meet it. The runtime notices that every goroutine is asleep and stops the program, which is a much better failure than a silent hang.","id":"concurrency.unbuffered-rendezvous","objective":"Say what blocks, and for how long, on a channel with no buffer.","task":{"predict":{"answer":"It deadlocks: fatal error: all goroutines are asleep - deadlock!\n\nThe send blocks waiting for a receiver, and the only goroutine that could receive is the one already blocked sending. make(chan string, 1) would let the send complete into the buffer, and the program would print hello.","question":"What happens, and would a buffer of one change it?","source":"package main\n\nfunc main() {\n\tready := make(chan string)\n\tready <- \"hello\"\n\tprintln(<-ready)\n}"}},"title":"An unbuffered channel is a meeting"},{"conceptTags":["concurrency.goroutine-leak","concurrency.waitgroup"],"explanation":"go f() starts f and immediately continues. There is no future to await and no value to collect, so the result has to come back through a channel or a shared variable protected by something.\n\nThe second half matters just as much: when main returns, the program exits and every remaining goroutine simply stops. A goroutine still blocked at that moment did not fail — it was never finished.","id":"concurrency.no-handle","objective":"Get a result out of a goroutine, and know when the program stops waiting.","task":{"predict":{"answer":"No.\n\nmain returns as soon as it receives from results, and nothing makes it wait for the second goroutine. It may print, may not, and the program is wrong either way if the output matters.","question":"Is the second goroutine guaranteed to print?","source":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\tresults := make(chan int)\n\tgo func() { results <- 42 }()\n\tgo func() { fmt.Println(\"this may never print\") }()\n\tfmt.Println(<-results)\n}"}},"title":"go returns nothing"},{"conceptTags":["concurrency.goroutine-leak"],"explanation":"Starting a goroutine creates an obligation: identify who asks it to stop and who observes that it has stopped. Canceling a context closes a signal; it does not terminate arbitrary Go code. Every blocking point must cooperate or have another bounded exit.","id":"concurrency.cancel-and-join","objective":"Design a worker so it can stop waiting and its owner can wait for it to finish.","task":{"reading":{}},"title":"Cancellation is a request; joining proves exit"},{"conceptTags":["concurrency.channel-close"],"explanation":"Closing a channel says that no more values will be sent. Give that decision to the producer, or to a coordinator that knows all producers have finished. A receiver should not close a stream while senders may still use it.\n\nReceivers can drain a closed buffered channel. `v, ok := <-ch` reports false only when the channel is closed and empty; `for v := range ch` then ends. Sending after close and closing twice both panic.","id":"concurrency.channel-close","idiomaticSolution":"func squares(n int) <-chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tdefer close(out)\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tout <- i * i\n\t\t}\n\t}()\n\treturn out\n}","objective":"Decide who closes a channel, and why the other side must not.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestSquaresClosesWhenDone(t *testing.T) {\n\tvar got []int\n\tfor value := range squares(3) {\n\t\tgot = append(got, value)\n\t}\n\tif len(got) != 3 || got[0] != 1 || got[2] != 9 {\n\t\tt.Fatalf(\"squares produced %v\", got)\n\t}\n}","starter":"package main\n\n// squares should send each square and then let the consumer's range\n// loop finish on its own.\nfunc squares(n int) <-chan int {\n\tout := make(chan int)\n\tgo func() {\n\t\tfor i := 1; i <= n; i++ {\n\t\t\tout <- i * i\n\t\t}\n\t}()\n\treturn out\n}\n\nfunc main() {}"}},"title":"The sender closes, the receiver ranges"},{"conceptTags":["concurrency.select","context.cancel","context.first-parameter"],"explanation":"select blocks until one of its cases can proceed, and picks randomly among those that are ready. Adding a case for <-ctx.Done() turns any wait into a cancellable one.\n\nThe convention that makes this composable: context is the first parameter, it is passed rather than stored, and cancel is always deferred so the resources behind it are released on every path.","id":"concurrency.select-context","idiomaticSolution":"func waitFor(ctx context.Context, values <-chan int) (int, error) {\n\tselect {\n\tcase value := <-values:\n\t\treturn value, nil\n\tcase <-ctx.Done():\n\t\treturn 0, ctx.Err()\n\t}\n}","objective":"Make a blocking operation cancellable without a flag or a kill switch.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n)\n\nfunc TestWaitForCancelled(t *testing.T) {\n\tctx, cancel := context.WithCancel(context.Background())\n\tcancel()\n\t_, err := waitFor(ctx, make(chan int))\n\tif !errors.Is(err, context.Canceled) {\n\t\tt.Fatalf(\"err = %v, want context.Canceled\", err)\n\t}\n}\n\nfunc TestWaitForValue(t *testing.T) {\n\tvalues := make(chan int, 1)\n\tvalues <- 7\n\tgot, err := waitFor(context.Background(), values)\n\tif err != nil || got != 7 {\n\t\tt.Fatalf(\"waitFor = %d, %v\", got, err)\n\t}\n}","starter":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n)\n\n// waitFor should return ctx.Err() when the context is cancelled\n// before a value arrives.\nfunc waitFor(ctx context.Context, values <-chan int) (int, error) {\n\treturn <-values, nil\n}\n\nfunc main() { _ = errors.New }"}},"title":"select waits on several things; context says stop"},{"conceptTags":["concurrency.mutex"],"explanation":"A channel is useful for transferring values and coordinating ownership. A mutex protects shared state that remains in place. Choose the mechanism that makes the invariant and its owner easiest to understand; neither mechanism is always faster.\n\nKeep the mutex next to the data it protects and use the same locking rule for every read and write participating in the invariant. A small, clearly bounded critical section is easier to maintain than a lock whose protected state is scattered.","id":"concurrency.mutex","idiomaticSolution":"func NewCounter() *Counter {\n\treturn &Counter{count: map[string]int{}}\n}\n\nfunc (c *Counter) Add(key string) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.count[key]++\n}\n\nfunc (c *Counter) Get(key string) int {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.count[key]\n}","objective":"Choose between a mutex and a channel for a given problem.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc TestCounterIsSafeUnderConcurrency(t *testing.T) {\n\tc := NewCounter()\n\tif c == nil {\n\t\tt.Fatal(\"NewCounter returned nil\")\n\t}\n\n\tvar wg sync.WaitGroup\n\tfor range 50 {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tc.Add(\"hits\")\n\t\t}()\n\t}\n\twg.Wait()\n\n\tif got := c.Get(\"hits\"); got != 50 {\n\t\tt.Errorf(\"Get = %d, want 50\", got)\n\t}\n\tif got := c.Get(\"missing\"); got != 0 {\n\t\tt.Errorf(\"an absent key should be 0, got %d\", got)\n\t}\n}","starter":"package main\n\nimport \"sync\"\n\n// Counter should be safe for many goroutines at once.\ntype Counter struct {\n\tmu    sync.Mutex\n\tcount map[string]int\n}\n\nfunc NewCounter() *Counter {\n\treturn nil\n}\n\nfunc (c *Counter) Add(key string) {}\n\nfunc (c *Counter) Get(key string) int { return 0 }\n\nfunc main() {}"}},"title":"A mutex is for state; a channel is for handing over"},{"conceptTags":["concurrency.waitgroup","concurrency.channel-close"],"explanation":"A fixed number of workers bounds concurrent processing. The producer sends jobs and closes the input stream after the last job. Workers consume it until it is drained. A coordinator waits for every worker before closing the output stream.\n\nResults may need to be consumed while jobs are still being produced, or backpressure can deadlock the producer and workers. Add cancellation deliberately, and test termination as well as returned values.","id":"concurrency.worker-pool","idiomaticSolution":"func Squares(numbers []int, workers int) []int {\n\tin, out := make(chan int), make(chan int)\n\n\tvar wg sync.WaitGroup\n\tfor range workers {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tfor n := range in {\n\t\t\t\tout <- n * n\n\t\t\t}\n\t\t}()\n\t}\n\n\tgo func() {\n\t\tdefer close(in)\n\t\tfor _, n := range numbers {\n\t\t\tin <- n\n\t\t}\n\t}()\n\n\tgo func() {\n\t\twg.Wait()\n\t\tclose(out)\n\t}()\n\n\tresults := make([]int, 0, len(numbers))\n\tfor r := range out {\n\t\tresults = append(results, r)\n\t}\n\treturn results\n}","objective":"Build a fixed set of workers that finishes cleanly.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"sort\"\n\t\"testing\"\n)\n\nfunc TestSquaresReturnsEveryResult(t *testing.T) {\n\tgot := Squares([]int{1, 2, 3, 4, 5}, 3)\n\tsort.Ints(got)\n\n\twant := []int{1, 4, 9, 16, 25}\n\tif len(got) != len(want) {\n\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t}\n\tfor i := range want {\n\t\tif got[i] != want[i] {\n\t\t\tt.Fatalf(\"got %v, want %v\", got, want)\n\t\t}\n\t}\n\tif len(Squares(nil, 2)) != 0 {\n\t\tt.Error(\"no input should give no results, and should still return\")\n\t}\n}","starter":"package main\n\n// Squares runs the numbers through workers goroutines and returns\n// every square. Order does not matter; finishing does.\nfunc Squares(numbers []int, workers int) []int {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"The worker pool, written once"},{"conceptTags":["services.capacity"],"explanation":"Concurrency is how work overlaps. Capacity is how much useful work the system can sustain. A thousand waiting goroutines do not give Redis a thousand extra cores or increase a database connection budget. They do consume memory, queue time and cancellation bookkeeping.","id":"concurrency.bounded-work","objective":"Bound active workers and queued work according to the resource that actually limits throughput.","task":{"reading":{}},"title":"More goroutines are not more capacity"},{"conceptTags":["concurrency.buffered","concurrency.deadlock"],"explanation":"The Tour's \"Buffered Channels\" page: `make(chan int, 100)` sends without a receiver until the buffer is full, and receives without a sender until it is empty. An unbuffered channel is a rendezvous. A buffered one is a mailbox of a known size.\n\nThe deadlock people then write is filling a buffer of 1 with two sends from the only goroutine there is. The buffer does not make the channel unbounded. It makes the bound visible in the `make`.","id":"concurrency.buffered","idiomaticSolution":"func Fill(n int) []int {\n\tch := make(chan int, n)\n\tfor i := 0; i < n; i++ {\n\t\tch <- i\n\t}\n\tclose(ch)\n\tout := make([]int, 0, n)\n\tfor v := range ch {\n\t\tout = append(out, v)\n\t}\n\treturn out\n}","objective":"Send n values on a channel of capacity n without another goroutine.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestFillDoesNotNeedAPartner(t *testing.T) {\n\tgot := Fill(4)\n\tif len(got) != 4 {\n\t\tt.Fatalf(\"got %v, want four values\", got)\n\t}\n\tfor i, v := range got {\n\t\tif v != i {\n\t\t\tt.Fatalf(\"got %v\", got)\n\t\t}\n\t}\n\tif len(Fill(0)) != 0 {\n\t\tt.Error(\"n == 0 should return an empty slice\")\n\t}\n}","starter":"package main\n\n// Fill sends 0..n-1 on a channel of capacity n, closes it, and\n// returns what a range reads back. It must not start a goroutine.\nfunc Fill(n int) []int {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"A buffer is a mailbox, not a meeting"},{"conceptTags":["concurrency.range-channel","concurrency.channel-close"],"explanation":"The Tour's \"Range and Close\" page: `v, ok := <-ch` sets ok to false once the channel is closed and empty. `for v := range ch` is that loop written once. Only the sender closes. Sending after a close panics. Closing is not required for the garbage collector — only for telling a range there is nothing more.\n\nChannels are not files. Most of them never close, because nobody is ranging. Close when a range (or an ok-receive) needs the signal.","id":"concurrency.range-and-close","idiomaticSolution":"func Drain(ch <-chan int) []int {\n\tout := []int{}\n\tfor v := range ch {\n\t\tout = append(out, v)\n\t}\n\treturn out\n}","objective":"Drain a channel with range, and close it from the sender.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestDrainReadsUntilClose(t *testing.T) {\n\tch := make(chan int, 3)\n\tch <- 2\n\tch <- 4\n\tch <- 6\n\tclose(ch)\n\tgot := Drain(ch)\n\tif len(got) != 3 || got[0] != 2 || got[2] != 6 {\n\t\tt.Fatalf(\"got %v, want [2 4 6]\", got)\n\t}\n\tif len(Drain(closedEmpty())) != 0 {\n\t\tt.Error(\"an already-closed channel should drain as empty\")\n\t}\n}\n\nfunc closedEmpty() <-chan int {\n\tch := make(chan int)\n\tclose(ch)\n\treturn ch\n}","starter":"package main\n\n// Drain reads every value until ch closes and returns them in\n// the order they arrived.\nfunc Drain(ch <-chan int) []int {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"range over a channel ends when it closes"},{"conceptTags":["concurrency.select-default","concurrency.select"],"explanation":"The Tour's \"Default Selection\" page: a `default` case runs when no other case is ready, so the select returns instead of blocking. That is how you poll a channel, and how you try a send without parking the goroutine.\n\nWithout default, select waits. With it, \"nothing ready\" is a value you handle, not a hang. A busy loop of default-selects is a spin; use it for a single try, not as a substitute for a timer.","id":"concurrency.select-default","idiomaticSolution":"func TryRecv(ch <-chan int) (int, bool) {\n\tselect {\n\tcase v := <-ch:\n\t\treturn v, true\n\tdefault:\n\t\treturn 0, false\n\t}\n}","objective":"Receive from a channel if a value is ready, and return if it is not.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestTryRecvDoesNotBlock(t *testing.T) {\n\tempty := make(chan int)\n\tif _, ok := TryRecv(empty); ok {\n\t\tt.Fatal(\"an empty channel is not ready\")\n\t}\n\n\tready := make(chan int, 1)\n\tready <- 7\n\tv, ok := TryRecv(ready)\n\tif !ok || v != 7 {\n\t\tt.Fatalf(\"got %d, %t; want 7, true\", v, ok)\n\t}\n\tif _, ok := TryRecv(ready); ok {\n\t\tt.Fatal(\"the channel should be empty after one receive\")\n\t}\n}","starter":"package main\n\n// TryRecv returns the next value and true when one is ready,\n// or 0 and false without waiting.\nfunc TryRecv(ch <-chan int) (int, bool) {\n\treturn <-ch, true\n}\n\nfunc main() {}"}},"title":"default makes select try, not wait"},{"conceptTags":["concurrency.channel-direction","concurrency.channel-close"],"explanation":"The Tour writes `ch <- v` and `v := <-ch` and then, in Effective Go, the type itself carries the arrow: `chan<- int` is send-only, `<-chan int` is receive-only. A function that only produces values should take `chan<- T`. The compiler then refuses a receive in that body, which is the whole point — the restriction is the API.\n\nConversion is one way: a bidirectional channel may be passed where a directional one is wanted. The other direction does not compile. Close is a send-side operation, so it belongs on `chan<- T`.","id":"concurrency.direction","idiomaticSolution":"func Produce(out chan<- int, values []int) {\n\tdefer close(out)\n\tfor _, v := range values {\n\t\tout <- v\n\t}\n}","objective":"Write a producer that takes chan<- int and closes it.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestProduceSendsAndCloses(t *testing.T) {\n\tout := make(chan int, 4)\n\tProduce(out, []int{1, 3, 5})\n\tvar got []int\n\tfor v := range out {\n\t\tgot = append(got, v)\n\t}\n\tif len(got) != 3 || got[0] != 1 || got[2] != 5 {\n\t\tt.Fatalf(\"got %v, want [1 3 5]\", got)\n\t}\n}\n\nfunc TestProduceAcceptsSendOnly(t *testing.T) {\n\t// If Produce takes chan int instead of chan<- int this still\n\t// compiles, but the lesson's idiomatic answer is the type.\n\tout := make(chan int)\n\tgo Produce(out, nil)\n\tfor range out {\n\t}\n}","starter":"package main\n\n// Produce sends every value and then closes out. The parameter\n// is send-only: a receive in this function should not compile.\nfunc Produce(out chan<- int, values []int) {}\n\nfunc main() {}"}},"title":"The arrow in the type is who may send"},{"conceptTags":["concurrency.once","concurrency.mutex"],"explanation":"Effective Go and the sync docs: `Once.Do(f)` runs f once, even when many goroutines call Do at the same time. After that, Do is a no-op. It is the right shape for a lazy setup that must not run twice — registering a driver, reading a config, seeding a generator.\n\nDo not copy an Once after it has been used. Do not call Do with a different f and expect that second f to run. The once is on the Once, not on the function value.","id":"concurrency.once","idiomaticSolution":"func Call(once *sync.Once, fn func()) {\n\tonce.Do(fn)\n}","objective":"Initialise shared state without a lock you have to remember.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"sync\"\n\t\"testing\"\n)\n\nfunc TestCallRunsOnce(t *testing.T) {\n\tvar once sync.Once\n\tn := 0\n\tCall(&once, func() { n++ })\n\tCall(&once, func() { n++ })\n\tif n != 1 {\n\t\tt.Fatalf(\"n = %d, want 1\", n)\n\t}\n}","starter":"package main\n\nimport \"sync\"\n\n// Call runs fn through once. Two calls must run fn once.\nfunc Call(once *sync.Once, fn func()) {\n\tfn()\n}\n\nfunc main() {}"}},"title":"sync.Once runs a function one time, for everyone"},{"conceptTags":["concurrency.waitgroup-go"],"explanation":"A request owns more than the act of starting goroutines. It must know when its work has stopped and who retains the results. Go 1.25 added WaitGroup.Go, which combines task registration and launch. It reduces a common Add/launch ordering mistake without supplying cancellation, an error result or a concurrency budget.","id":"concurrency.waitgroup-go","objective":"Use modern WaitGroup task ownership and explain its limits.","task":{"reading":{}},"title":"WaitGroup.Go joins tasks; it does not collect their errors"},{"conceptTags":["concurrency.synctest"],"explanation":"Tests that sleep for a guessed interval are slow and sensitive to machine load. testing/synctest is a standard package in Go 1.25 and later. It runs a test bubble with virtual time and coordinated goroutine waiting. It is useful for in-process protocols, not a simulator for a remote database or every operating-system event.","id":"concurrency.synctest","objective":"Use testing/synctest to assert a concurrent timeline deterministically.","task":{"reading":{}},"title":"Test time and cancellation without sleeping on the wall clock"},{"conceptTags":["concurrency.errgroup"],"explanation":"golang.org/x/sync/errgroup is a versioned external module, not part of sync. WithContext supplies a derived cancellation context and Wait returns a task error. Tasks must still cooperate with cancellation, and a limit on active tasks is different from a limit on queued input bytes or waiting requests.","id":"concurrency.errgroup","objective":"Coordinate fallible parallel work without confusing cancellation with joining.","task":{"reading":{}},"title":"errgroup: errors, cancellation and a real concurrency limit"},{"conceptTags":["concurrency.atomic-snapshots"],"explanation":"An atomic load or store synchronizes an operation on the atomic value. It does not recursively make the object graph immutable or protect a later map mutation. A useful read-mostly pattern builds a complete independent configuration, publishes one pointer and lets readers hold that immutable snapshot. All fields that must agree belong to the same published value.","id":"concurrency.atomic-snapshots","objective":"Publish one consistent snapshot and preserve ownership of its reachable maps and slices.","task":{"reading":{}},"title":"Atomic publication is safe only when the published snapshot stays immutable"},{"conceptTags":["concurrency.lock-ownership"],"explanation":"The presence of a mutex in a struct does not prove that every operation locks the same mutex. A value receiver or assignment can copy the lock while retaining a reference to the same map. Likewise, sync.Map protects its own operations but cannot infer an invariant spanning several keys. Define the state that must change together and keep one synchronization owner for that state.","id":"concurrency.lock-ownership","objective":"Choose synchronization around related state and return snapshots rather than copied lock owners.","task":{"reading":{}},"title":"Mutex, RWMutex and sync.Map: protect the invariant and do not copy the lock"}],"summary":"Goroutines, channel ownership, select, buffers and who may send.","title":"Concurrency","translationNote":"A goroutine is not a promise and not a thread. It has no handle, no return value and no join — which is why channels and WaitGroups exist, and why \"who closes this channel\" is a design question rather than a detail."},{"id":"stdlib","lessons":[{"conceptTags":["stdlib.io","interfaces.size"],"explanation":"io.Reader has Read. io.Writer has Write. Files, network connections, HTTP bodies, gzip streams, strings.Reader and bytes.Buffer all satisfy one or both.\n\nAccepting them instead of a concrete type is what makes Go code testable without mocks: the test passes a bytes.Buffer and reads the result back.","id":"stdlib.io","idiomaticSolution":"func WriteUpper(dst io.Writer, src io.Reader) error {\n\tdata, err := io.ReadAll(src)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"read: %w\", err)\n\t}\n\tif _, err := io.WriteString(dst, strings.ToUpper(string(data))); err != nil {\n\t\treturn fmt.Errorf(\"write: %w\", err)\n\t}\n\treturn nil\n}","objective":"Write a function that works on a file, a string and a test buffer.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n)\n\nfunc TestWriteUpper(t *testing.T) {\n\tvar out bytes.Buffer\n\tif err := WriteUpper(&out, strings.NewReader(\"go forge\")); err != nil {\n\t\tt.Fatalf(\"WriteUpper returned %v\", err)\n\t}\n\tif got := out.String(); got != \"GO FORGE\" {\n\t\tt.Errorf(\"out = %q, want %q\", got, \"GO FORGE\")\n\t}\n}","starter":"package main\n\nimport (\n\t\"os\"\n\t\"strings\"\n)\n\n// WriteUpper copies src to dst, upper-cased. It should work with any\n// reader and writer, not just files.\nfunc WriteUpper(dst *os.File, src *strings.Reader) error {\n\treturn nil\n}\n\nfunc main() {}"}},"title":"Two interfaces, one method each"},{"conceptTags":["stdlib.json"],"explanation":"encoding/json maps struct fields by name, and a tag overrides that. Only exported fields are considered, which is the first thing that catches people: a lower-case field is invisible to the encoder with no error.\n\nUnmarshal leaves fields absent from the input untouched rather than zeroing them, so decoding into a reused struct can silently keep old values.","id":"stdlib.json","objective":"Control field names, omit empties, and know what unmarshalling leaves untouched.","task":{"predict":{"answer":"{\"host\":\"localhost\"}\n\nport was zero and carries omitempty, so it is dropped. secret is unexported, so encoding/json cannot see it at all — no tag would change that.","question":"What is printed, and where did port and secret go?","source":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\ntype Config struct {\n\tHost    string `json:\"host\"`\n\tPort    int    `json:\"port,omitempty\"`\n\tsecret  string\n}\n\nfunc main() {\n\tdata, _ := json.Marshal(Config{Host: \"localhost\", secret: \"hidden\"})\n\tfmt.Println(string(data))\n}"}},"title":"Struct tags are the JSON schema"},{"conceptTags":["stdlib.json-v2-contracts"],"explanation":"Go 1.27 includes encoding/json/v2 without an experiment flag. Keeping encoding/json preserves its v1 behavior; adopting the v2 API is a separate decision. A compiling change can still alter a mobile model, persisted event or generated client. Write the expected wire representation before migrating.","id":"stdlib.json-v2-contracts","objective":"Compare null, empty and omitted JSON values before changing a public API.","task":{"reading":{}},"title":"JSON v2: migrate behavior, not just imports"},{"conceptTags":["stdlib.time"],"explanation":"`time.Duration` is an int64 counting nanoseconds, and the constants are what make it readable: `5 * time.Second` is a multiplication, not a function call. That is also the trap — a bare `5` is five nanoseconds, and `time.Sleep(5)` requests five nanoseconds, not five seconds. Scheduler timing may make the actual wait longer.\n\nTwo more worth knowing on sight: `end.Sub(start)` gives a Duration, and comparing Times uses Before, After and Equal rather than the operators, because a Time carries a monotonic reading as well as a wall clock.","id":"stdlib.time","objective":"Write a timeout without wondering what unit it is in.","task":{"predict":{"answer":"1m30s\n1.5\n36h0m0s\ntrue","question":"What does this print? Durations print themselves.","source":"package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n)\n\nfunc main() {\n\td := 90 * time.Second\n\tfmt.Println(d)\n\tfmt.Println(d.Minutes())\n\n\tstart := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)\n\tend := start.Add(36 * time.Hour)\n\tfmt.Println(end.Sub(start))\n\tfmt.Println(end.After(start))\n}"}},"title":"A Duration is a number of nanoseconds with a type"},{"conceptTags":["stdlib.sort"],"explanation":"`slices.SortFunc` takes a comparison that returns a negative number, zero or a positive one — not a bool. That trips people coming from languages where the comparator answers \"is a before b\". `cmp.Compare` does the right thing for any ordered type and is what the comparison should usually be built from.\n\nFor a second key, compare the first and fall through only when it is equal. That is the whole pattern, and it is worth writing out once.","id":"stdlib.sort","idiomaticSolution":"func SortReleases(releases []Release) {\n\tslices.SortFunc(releases, func(a, b Release) int {\n\t\tif c := cmp.Compare(a.Year, b.Year); c != 0 {\n\t\t\treturn c\n\t\t}\n\t\treturn cmp.Compare(a.Name, b.Name)\n\t})\n}","objective":"Sort a slice of structs by two keys.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestSortReleases(t *testing.T) {\n\treleases := []Release{\n\t\t{\"zeta\", 2020},\n\t\t{\"alpha\", 2020},\n\t\t{\"beta\", 2018},\n\t}\n\tSortReleases(releases)\n\n\twant := []Release{{\"beta\", 2018}, {\"alpha\", 2020}, {\"zeta\", 2020}}\n\tfor i := range want {\n\t\tif releases[i] != want[i] {\n\t\t\tt.Fatalf(\"got %v, want %v\", releases, want)\n\t\t}\n\t}\n}","starter":"package main\n\ntype Release struct {\n\tName string\n\tYear int\n}\n\n// SortReleases orders by year ascending, and by name for\n// releases from the same year. It sorts in place.\nfunc SortReleases(releases []Release) {}\n\nfunc main() {}"}},"title":"Sorting by whatever you like"},{"conceptTags":["context.cancel","context.first-parameter"],"explanation":"A context is how a caller says \"stop, I no longer need this\". Anything that could block — a network call, a sleep, a channel receive — should take one and should select on `ctx.Done()` alongside whatever it was waiting for. A function that ignores its context is a function nothing can cancel.\n\n`ctx.Err()` says which happened: `context.Canceled` when someone called cancel, `context.DeadlineExceeded` when the timeout ran out. Returning it directly is usually right — the caller already knows what it asked for.","id":"stdlib.context","idiomaticSolution":"func WaitFor(ctx context.Context, d time.Duration) error {\n\ttimer := time.NewTimer(d)\n\tdefer timer.Stop()\n\n\tselect {\n\tcase <-timer.C:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}","objective":"Make a function that waits stop waiting when told to.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc TestWaitForRespectsTheContext(t *testing.T) {\n\tif err := WaitFor(context.Background(), time.Millisecond); err != nil {\n\t\tt.Errorf(\"a short wait should succeed, got %v\", err)\n\t}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)\n\tdefer cancel()\n\n\tstart := time.Now()\n\terr := WaitFor(ctx, 5*time.Second)\n\tif !errors.Is(err, context.DeadlineExceeded) {\n\t\tt.Fatalf(\"err = %v, want DeadlineExceeded\", err)\n\t}\n\tif time.Since(start) > time.Second {\n\t\tt.Error(\"WaitFor kept waiting after the context finished\")\n\t}\n}","starter":"package main\n\nimport (\n\t\"context\"\n\t\"time\"\n)\n\n// WaitFor returns nil once d has passed, or the context's error\n// if the context finishes first. It must not outlive either.\nfunc WaitFor(ctx context.Context, d time.Duration) error {\n\ttime.Sleep(d)\n\treturn nil\n}\n\nfunc main() {}"}},"title":"Every blocking call should take a context"},{"conceptTags":["stdlib.http","interfaces.size"],"explanation":"Go's own \"Writing Web Applications\" tutorial and the Tour's \"where to go next\" both land on `http.Handler`. It is one method:\n\n    ServeHTTP(http.ResponseWriter, *http.Request)\n\n`http.HandlerFunc` turns a function into that type. `http.ServeMux` is a Handler that dispatches to others. The sandbox has no network, so this lesson uses `httptest`: the types are real, the listen is not. A function that accepts `http.Handler` can be tested the same way in any Go module.","id":"stdlib.http","idiomaticSolution":"func Hello() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.URL.Path != \"/hello\" {\n\t\t\thttp.NotFound(w, r)\n\t\t\treturn\n\t\t}\n\t\tio.WriteString(w, \"hi\")\n\t})\n}","objective":"Serve /hello from an in-memory request, with no listen.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n)\n\nfunc TestHello(t *testing.T) {\n\th := Hello()\n\treq := httptest.NewRequest(http.MethodGet, \"/hello\", nil)\n\trec := httptest.NewRecorder()\n\th.ServeHTTP(rec, req)\n\tif rec.Code != 200 {\n\t\tt.Fatalf(\"status %d, want 200\", rec.Code)\n\t}\n\tbody, _ := io.ReadAll(rec.Result().Body)\n\tif string(body) != \"hi\" {\n\t\tt.Fatalf(\"body %q, want hi\", body)\n\t}\n\n\tmiss := httptest.NewRecorder()\n\th.ServeHTTP(miss, httptest.NewRequest(http.MethodGet, \"/nope\", nil))\n\tif miss.Code != 404 {\n\t\tt.Fatalf(\"missing path status %d, want 404\", miss.Code)\n\t}\n}","starter":"package main\n\nimport \"net/http\"\n\n// Hello answers GET /hello with \"hi\" and 404 for anything else.\nfunc Hello() http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})\n}\n\nfunc main() {}"}},"title":"http.Handler is one method, like Reader"},{"conceptTags":["stdlib.strconv","errors.explicit-check"],"explanation":"The Tour's Errors page uses `strconv.Atoi` as the example of a function that returns `(int, error)`. That is the package: no `ParseInt` surprises in everyday code, no `fmt.Sscan` for a single number. `Atoi` is `ParseInt(s, 10, 0)` with a shorter name.\n\nFailure is an error, not a panic and not a zero you are meant to guess at. Discarding that error is how `\"x\"` becomes port 0.","id":"stdlib.strconv","idiomaticSolution":"func ParsePort(raw string) (int, error) {\n\tn, err := strconv.Atoi(raw)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif n < 1 || n > 65535 {\n\t\treturn 0, fmt.Errorf(\"port %d out of range\", n)\n\t}\n\treturn n, nil\n}","objective":"Parse a port with Atoi and reject anything outside 1…65535.","task":{"compile":{"hiddenTest":"package main\n\nimport \"testing\"\n\nfunc TestParsePort(t *testing.T) {\n\tn, err := ParsePort(\"8080\")\n\tif err != nil || n != 8080 {\n\t\tt.Fatalf(\"8080 -> %d, %v\", n, err)\n\t}\n\tif _, err := ParsePort(\"nope\"); err == nil {\n\t\tt.Fatal(\"text must be an error\")\n\t}\n\tif _, err := ParsePort(\"0\"); err == nil {\n\t\tt.Fatal(\"0 is not a port\")\n\t}\n\tif _, err := ParsePort(\"70000\"); err == nil {\n\t\tt.Fatal(\"70000 is out of range\")\n\t}\n}","starter":"package main\n\n// ParsePort accepts 1 through 65535. Anything else is an error,\n// including text that is not a number.\nfunc ParsePort(raw string) (int, error) {\n\treturn 0, nil\n}\n\nfunc main() {}"}},"title":"strconv is how text becomes a number"},{"conceptTags":["stdlib.image"],"explanation":"`image.Image` describes pixels through three methods: `ColorModel`, `Bounds` and `At`. A decoded PNG produces an image value; the encoded PNG file itself does not implement that interface. A type you write can implement the same pixel contract.\n\n`image/draw` and `image/png` work with image interfaces rather than requiring one concrete bitmap type. This lesson supplies a solid rectangle with chosen bounds and color; encoding that image is a separate step.","id":"stdlib.image","idiomaticSolution":"func (s Solid) Bounds() image.Rectangle {\n\treturn image.Rect(0, 0, s.W, s.H)\n}\nfunc (s Solid) At(x, y int) color.Color { return s.C }","objective":"Implement a solid-colour image the standard library will accept.","task":{"compile":{"hiddenTest":"package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n\t\"testing\"\n)\n\nfunc TestSolidIsAnImage(t *testing.T) {\n\tvar img image.Image = Solid{W: 4, H: 3, C: color.RGBA{1, 2, 3, 255}}\n\tb := img.Bounds()\n\tif b.Dx() != 4 || b.Dy() != 3 {\n\t\tt.Fatalf(\"bounds %v, want 4x3\", b)\n\t}\n\tgot, ok := img.At(1, 1).(color.RGBA)\n\tif !ok || got != (color.RGBA{1, 2, 3, 255}) {\n\t\tt.Fatalf(\"At = %v\", img.At(1, 1))\n\t}\n}","starter":"package main\n\nimport (\n\t\"image\"\n\t\"image/color\"\n)\n\ntype Solid struct {\n\tW, H int\n\tC    color.RGBA\n}\n\nfunc (s Solid) ColorModel() color.Model { return color.RGBAModel }\nfunc (s Solid) Bounds() image.Rectangle { return image.Rectangle{} }\nfunc (s Solid) At(x, y int) color.Color { return color.RGBA{} }\n\nfunc main() {}"}},"title":"image.Image is three methods, not a file"},{"conceptTags":["stdlib.borrowed-buffers"],"explanation":"A byte slice can be a borrowed window rather than an owned result. bytes.Buffer.Bytes exposes unread storage, and Scanner.Bytes exposes a token with a limited lifetime. The type []byte does not express that lifetime. Draw the owner, the view and the next mutation before deciding whether to copy.","id":"stdlib.borrowed-buffers","objective":"Trace bytes.Buffer and Scanner views, then make retained results independent at a lifetime boundary.","task":{"reading":{}},"title":"Borrow bytes briefly; copy before their owner changes"},{"conceptTags":["stdlib.json-presence"],"explanation":"A JSON object can omit a member, contain null, or contain a concrete zero value. Go fields alone do not always preserve those distinctions. An update that sets enabled to false must not silently become an instruction to leave enabled unchanged. Start with a state table for the operation.","id":"stdlib.json-presence","objective":"Choose omitempty, omitzero and request presence models from the endpoint contract.","task":{"reading":{}},"title":"JSON presence: omitted, zero and null are different states"},{"conceptTags":["stdlib.json-input-policy"],"explanation":"Successful decoding proves only that input was accepted under the decoder policy. It does not authorize the caller or establish a valid business transition. V2 rejects duplicate names and invalid UTF-8 by default; exact field-name matching and unknown-member rejection are separate settings.","id":"stdlib.json-input-policy","objective":"Separate JSON syntax acceptance, unknown-member policy and domain validation.","task":{"reading":{}},"title":"Strict JSON input: reject ambiguity before side effects"},{"conceptTags":["stdlib.timer-contracts"],"explanation":"Timers have both an API contract and version-dependent implementation behavior. Modern Go timer channels avoid the old buffered stale-value behavior under the documented module/runtime conditions, but this does not let several goroutines reset, receive and decide business state without a protocol. Treat a timer as one owner’s scheduling tool and separately define which events may commit work.","id":"stdlib.timer-contracts","objective":"Explain Stop/Reset behavior, timer ownership and why select is not a priority statement.","task":{"reading":{}},"title":"Timers and cancellation: versioned semantics still need a single owner"},{"conceptTags":["stdlib.http-client-budgets"],"explanation":"A successful Client.Do means an HTTP response was received, not that the application operation succeeded. An error page can still be a valid response, and a server can keep streaming bytes after the headers arrive. Reuse the client and transport, pass an operation context and bound both elapsed time and bytes consumed. Closing the body is necessary even when status handling returns early.","id":"stdlib.http-client-budgets","objective":"Own the client lifetime, close bodies and classify HTTP status separately from transport failure.","task":{"reading":{}},"title":"Outgoing HTTP: reuse the client and bound the response, not just the dial"}],"summary":"io.Reader and io.Writer, encoding/json, and testing without a framework.","title":"Standard library patterns","translationNote":"Go's survey lists getting more from the standard library as a top friction. The reason is usually not missing knowledge of a package but missing knowledge of two interfaces: once io.Reader and io.Writer click, a surprising share of third-party code stops being necessary.\n\nSome of this unit runs against in-memory transports rather than real sockets, because the sandbox has no network. The compilation and the types are real; only the transport is simulated, and every lesson says so where it applies."},{"id":"runtime","lessons":[{"conceptTags":["runtime.allocation"],"explanation":"Lifetime is the semantic question: how long must a value remain usable? Stack and heap placement are implementation choices used to satisfy that requirement. The compiler performs escape analysis; source syntax alone is not a dependable allocation profiler.","id":"runtime.stack-and-heap","objective":"Explain why returning a local address is safe and why allocation placement must be measured.","task":{"reading":{}},"title":"Stacks, escape analysis and object lifetimes"},{"conceptTags":["runtime.gc"],"explanation":"Garbage collection reclaims memory that the runtime determines is no longer reachable. It does not know that an application has lost interest in a cache entry, nor does it close a forgotten network connection on a useful schedule. Ownership still matters.","id":"runtime.gc-reachability","objective":"Follow references from roots and distinguish unreachable objects from unwanted live data.","task":{"reading":{}},"title":"What the garbage collector can and cannot free"},{"conceptTags":["runtime.gc"],"explanation":"A service pays for memory in more than one way: live objects occupy space, new allocations create work, and collection uses CPU. Tuning a single GC knob cannot repair an unbounded cache or a queue that retains every request body.","id":"runtime.gc-budget","objective":"Distinguish reducing live data from tuning collection frequency and respect a container memory limit.","task":{"reading":{}},"title":"GC cost, allocation rate and memory budgets"},{"conceptTags":["runtime.scheduler"],"explanation":"A goroutine is a Go execution task scheduled by the runtime. An OS thread is an operating-system execution resource. The runtime multiplexes tasks onto threads; counting goroutines therefore does not tell you how many cores are doing useful work.","id":"runtime.goroutines-and-threads","objective":"Explain concurrency versus parallel execution without assuming a goroutine is an OS thread.","task":{"reading":{}},"title":"Goroutines, OS threads and GOMAXPROCS"},{"conceptTags":["runtime.profiling"],"explanation":"A rising memory graph is a symptom. Before changing code, ask whether traffic grew, objects are retained, workers are stuck, or allocation churn became expensive. Different diagnostic tools answer different questions.","id":"runtime.profiles-and-leaks","objective":"Choose a heap profile, goroutine profile, CPU profile or trace to test a specific hypothesis.","task":{"reading":{}},"title":"Find a leak by following evidence"},{"conceptTags":["runtime.pool-ownership"],"explanation":"Pooling can reduce temporary allocation, but every Get and Put creates an ownership obligation. A former owner must stop using the object after Put. A result that still aliases the object violates that obligation even when the code compiles and a small benchmark looks fast.","id":"runtime.pool-ownership","objective":"Use sync.Pool with exclusive ownership, independent output and an explicit policy for oversized buffers.","task":{"reading":{}},"title":"A pool reuses temporary objects; it does not own your results"}],"summary":"Stacks, GC, goroutines, threads and diagnostic evidence.","title":"Runtime and memory","translationNote":"Read worked examples without compiling. Native service behavior can differ from the app's WebAssembly execution environment."},{"id":"services","lessons":[{"conceptTags":["stdlib.http"],"explanation":"A Go web service is more than a route callback. Every request consumes a connection, parsing work, application time and possibly downstream capacity. Give those resources explicit lifetimes. This lesson describes native server code; guest Go programs in the app cannot open network sockets.","id":"services.http-lifecycle","objective":"Separate request parsing, domain work, downstream deadlines and response writing.","task":{"reading":{}},"title":"An HTTP request has a lifecycle and a budget"},{"conceptTags":["services.gin"],"explanation":"Gin supplies routing, middleware and request/response helpers on top of net/http. It is useful when those conventions reduce repeated adapter code. It does not supply your domain model, persistence policy or downstream capacity, and a small API can also use the standard library.","id":"services.gin-routing","objective":"Read route groups, path parameters and injected dependencies in a small Gin API.","task":{"reading":{}},"title":"Gin routes are adapters, not the whole application"},{"conceptTags":["services.gin"],"explanation":"Decoded JSON is not yet trusted application input. A field can have the right Go type and still violate a business rule. Bound the body, handle decoding failure, then apply domain validation before writing to storage or calling another service.","id":"services.gin-validation","objective":"Follow JSON binding, size limits, validation and a safe error response.","task":{"reading":{}},"title":"Validate a request before doing side effects"},{"conceptTags":["services.redis"],"explanation":"Redis can be overwhelmed by too much work, large payloads, expensive commands or many clients competing for the same resources. Making every slice element a goroutine only moves pressure downstream. Treat the server, the network and the client pool as separate budgets.","id":"services.redis-capacity","objective":"Distinguish client pool limits, request deadlines, rate limits and bounded command batches.","task":{"reading":{}},"title":"Redis is fast; its capacity is still finite"},{"conceptTags":["services.capacity"],"explanation":"A cache is often added to reduce load, yet its failure path can multiply load. When a popular key expires, many callers may fetch the same value at once. When a timeout triggers retries at several layers, one user action can become many downstream operations.","id":"services.cache-stampede","objective":"Design a cache-miss path that avoids multiplying identical work and ambiguous retries.","task":{"reading":{}},"title":"Cache misses, retries and overload amplification"}],"summary":"HTTP, Gin, Redis and the capacity of downstream services.","title":"Go services","translationNote":"These reading lessons explain native service designs. They do not add guest network sockets or remote services to the iOS sandbox."},{"id":"architecture","lessons":[{"conceptTags":["architecture.boundaries"],"explanation":"Go packages provide namespaces and compile-time dependency boundaries. More packages do not automatically create a cleaner design. Start with behavior that changes together, then separate a boundary when it hides an implementation detail or makes a dependency direction clearer.","id":"architecture.package-boundaries","objective":"Choose cohesive package boundaries and keep concrete dependencies at the edges.","task":{"reading":{}},"title":"Packages follow responsibilities, not a diagram"},{"conceptTags":["architecture.boundaries"],"explanation":"Ports and adapters is a way to keep a use case independent of delivery and infrastructure details. It is useful when one behavior has several entry points or storage implementations. The value comes from dependency direction, not from the number of folders named domain.","id":"architecture.ports-and-adapters","objective":"Trace an HTTP adapter through an application operation to a storage port and compare test boundaries.","task":{"reading":{}},"title":"Ports and adapters with a real request"},{"conceptTags":["architecture.design"],"explanation":"Architecture is a choice about boundaries, change and failure. A modular monolith can keep strong internal boundaries with one deployment. Microservices can separate ownership and release schedules, but add remote calls, distributed failures, versioning and operational work.","id":"architecture.styles-and-clean-code","objective":"Compare a modular monolith, layered design and microservices using concrete operational tradeoffs.","task":{"reading":{}},"title":"Choose a style; keep the code easy to change"},{"conceptTags":["architecture.simple-monolith"],"explanation":"Keep a small application understandable without premature service boundaries. A command-line invoice tool can parse input, compute a result and print it in one process. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.simple-monolith","objective":"Keep a small application understandable without premature service boundaries.","task":{"reading":{}},"title":"Simple monolith: start with one executable"},{"conceptTags":["architecture.layered"],"explanation":"Separate responsibilities without confusing logical layers with deployed tiers. A layered service routes requests through transport, application logic and persistence. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.layered","objective":"Separate responsibilities without confusing logical layers with deployed tiers.","task":{"reading":{}},"title":"Layered architecture: transport, application, storage"},{"conceptTags":["architecture.modular-monolith"],"explanation":"Give business capabilities explicit APIs while retaining local transactions. A modular monolith groups capabilities such as billing and shipping behind package APIs. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.modular-monolith","objective":"Give business capabilities explicit APIs while retaining local transactions.","task":{"reading":{}},"title":"Modular monolith: boundaries inside one deployment"},{"conceptTags":["architecture.clean-onion"],"explanation":"Keep domain policy independent of framework and database details. Clean and Onion designs place domain rules near the center and technology at the edge. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.clean-onion","objective":"Keep domain policy independent of framework and database details.","task":{"reading":{}},"title":"Clean and Onion: dependencies point toward policy"},{"conceptTags":["architecture.vertical-slice"],"explanation":"Keep feature changes together without duplicating shared invariants. A vertical slice groups request parsing, application behavior and persistence for one capability, such as RenameProject. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.vertical-slice","objective":"Keep feature changes together without duplicating shared invariants.","task":{"reading":{}},"title":"Vertical slices: organize around a use case"},{"conceptTags":["architecture.ddd"],"explanation":"Model language and invariants before choosing storage or transport. Domain-driven design is a modeling approach, not a demand for microservices. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.ddd","objective":"Model language and invariants before choosing storage or transport.","task":{"reading":{}},"title":"DDD: bounded contexts and aggregates"},{"conceptTags":["architecture.cqrs"],"explanation":"Separate change rules from read shape without assuming two databases. CQRS separates the model that changes state from the model that answers questions. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.cqrs","objective":"Separate change rules from read shape without assuming two databases.","task":{"reading":{}},"title":"CQRS: different models for commands and queries"},{"conceptTags":["architecture.event-sourcing"],"explanation":"Distinguish a source of truth from ordinary logs and notifications. An event-sourced aggregate reconstructs state from accepted domain events. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.event-sourcing","objective":"Distinguish a source of truth from ordinary logs and notifications.","task":{"reading":{}},"title":"Event sourcing: state from a durable history"},{"conceptTags":["architecture.event-driven"],"explanation":"Treat duplicate delivery as normal and define the durable boundary. Event-driven systems decouple a producer from consumers through notifications or durable messages. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.event-driven","objective":"Treat duplicate delivery as normal and define the durable boundary.","task":{"reading":{}},"title":"Event-driven services: delivery and idempotency"},{"conceptTags":["architecture.microservices"],"explanation":"Extract a remote boundary only when its independence is valuable. A microservice owns a business capability, its data and its deployment. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.microservices","objective":"Extract a remote boundary only when its independence is valuable.","task":{"reading":{}},"title":"Microservices: pay for independent ownership"},{"conceptTags":["architecture.soa"],"explanation":"Compare service-oriented integration with smaller independently owned services. Service-oriented architecture organizes reusable business capabilities behind contracts, often across existing enterprise systems. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.soa","objective":"Compare service-oriented integration with smaller independently owned services.","task":{"reading":{}},"title":"SOA and RPC: stable service contracts"},{"conceptTags":["architecture.bff"],"explanation":"Compose client-specific views while retaining business ownership. A backend for frontend provides an API suited to a particular client, such as mobile. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.bff","objective":"Compose client-specific views while retaining business ownership.","task":{"reading":{}},"title":"BFF: an API shaped for one client"},{"conceptTags":["architecture.serverless"],"explanation":"Separate invocation mechanics from deterministic application behavior. A function platform manages execution capacity while your handler processes an invocation. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.serverless","objective":"Separate invocation mechanics from deterministic application behavior.","task":{"reading":{}},"title":"Serverless handlers: bounded work and retry-safe effects"},{"conceptTags":["architecture.pipes-filters"],"explanation":"Compose transformations while making backpressure and errors explicit. A pipes-and-filters design passes data through small stages such as decode, validate and transform. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.pipes-filters","objective":"Compose transformations while making backpressure and errors explicit.","task":{"reading":{}},"title":"Pipes and filters: data through independent stages"},{"conceptTags":["architecture.microkernel"],"explanation":"Extend behavior through contracts without assuming dynamic shared libraries. A microkernel or plugin architecture keeps a stable core and accepts extensions through a narrow contract. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.microkernel","objective":"Extend behavior through contracts without assuming dynamic shared libraries.","task":{"reading":{}},"title":"Microkernel: a small core with explicit extensions"},{"conceptTags":["architecture.web-queue-worker"],"explanation":"Separate request latency from background completion. A web-queue-worker system accepts a task, durably records it and lets a worker finish later. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"architecture.web-queue-worker","objective":"Separate request latency from background completion.","task":{"reading":{}},"title":"Web, queue, worker: make slow work durable"}],"summary":"Compare monoliths, layers, hexagonal and clean designs, DDD, CQRS, events and distributed services.","title":"Go architectures","translationNote":"Ratings are editorial fit for a task, not performance measurements. Styles overlap: compare boundaries, consistency and operational cost."},{"id":"clean-code","lessons":[{"conceptTags":["clean.names"],"explanation":"Make a caller understand units, results and ownership from the API. Names should reduce guesses at the call site. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.names","objective":"Make a caller understand units, results and ownership from the API.","task":{"reading":{}},"title":"Names that expose responsibility"},{"conceptTags":["clean.interfaces"],"explanation":"Describe a real substitution boundary without wrapping every concrete type. A consumer knows which behavior it needs. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.interfaces","objective":"Describe a real substitution boundary without wrapping every concrete type.","task":{"reading":{}},"title":"Small interfaces belong near the consumer"},{"conceptTags":["clean.errors"],"explanation":"Keep failure context useful without logging the same failure at every layer. An error value travels to the layer that can decide what to do: retry, map to a response or stop. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.errors","objective":"Keep failure context useful without logging the same failure at every layer.","task":{"reading":{}},"title":"Errors: preserve cause and choose one reporting boundary"},{"conceptTags":["clean.ownership"],"explanation":"Make it clear whether a caller lends, shares or transfers a buffer. A slice is a view of a backing array, so assignment does not copy its elements. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.ownership","objective":"Make it clear whether a caller lends, shares or transfers a buffer.","task":{"reading":{}},"title":"Ownership: copy mutable data deliberately"},{"conceptTags":["clean.configuration"],"explanation":"Turn invalid setup into an explicit startup error. A constructor is a useful boundary for validating configuration that should remain true for an object’s lifetime. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.configuration","objective":"Turn invalid setup into an explicit startup error.","task":{"reading":{}},"title":"Configuration: validate once at construction"},{"conceptTags":["clean.table-tests"],"explanation":"Test an observable contract with success and failure inputs. A table of cases makes differences explicit without copying the whole test body. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.table-tests","objective":"Test an observable contract with success and failure inputs.","task":{"reading":{}},"title":"Behavior tests: tables and boundary cases"},{"conceptTags":["clean.refactoring"],"explanation":"Separate a behavior-preserving edit from a new requirement. A safe refactor starts with the behavior that must stay stable, then changes one structure at a time. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.refactoring","objective":"Separate a behavior-preserving edit from a new requirement.","task":{"reading":{}},"title":"Refactoring: make the safe change small"},{"conceptTags":["clean.solid"],"explanation":"Translate responsibility, substitution and dependency inversion into Go contracts. Single responsibility concerns reasons to change. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"clean.solid","objective":"Translate responsibility, substitution and dependency inversion into Go contracts.","task":{"reading":{}},"title":"SOLID in Go: principles without class scaffolding"}],"summary":"Names, interfaces, errors, ownership, tests and safe refactoring.","title":"Clean code in Go","translationNote":"Prefer clear concrete code until a real boundary needs abstraction. Follow the worked examples and explain why each change helps."},{"id":"system-design","lessons":[{"conceptTags":["systems.transaction-boundary"],"explanation":"A transport handler can parse a request correctly while the application still commits only half of a business operation. Place the invariant in one use case and make its transaction boundary explicit. The adapter translates HTTP and errors; it does not independently commit each repository call. A Go interface alone cannot make two stores atomic.","id":"systems.transaction-boundary","objective":"Keep the business invariant and transaction boundary in the application service.","task":{"reading":{}},"title":"A use case owns its transaction, not its HTTP handler"},{"conceptTags":["systems.outbox-inbox"],"explanation":"Writing an order and publishing its event are two different side effects. A crash between them can leave a missing event; publishing first can announce a change that never commits. An outbox stores publication intent beside the business write in the same durable transaction. A separate relay retries it, and the consumer expects duplicates rather than claiming end-to-end exactly once.","id":"systems.outbox-inbox","objective":"Commit a business change and its publication intent together, then deduplicate delivery.","task":{"reading":{}},"title":"Outbox and inbox: close the database–broker gap"},{"conceptTags":["systems.sagas"],"explanation":"A reservation, payment authorization and shipment may belong to different services. They cannot usually share a database transaction. A saga records progress and issues commands whose effects can be retried or compensated. Compensation is another business operation, with its own failures, rather than a database rollback that erases everything that already happened.","id":"systems.sagas","objective":"Model a distributed workflow as durable states with explicit compensation and recovery.","task":{"reading":{}},"title":"Sagas: compensate business steps without pretending to roll back time"},{"conceptTags":["systems.compatibility"],"explanation":"A rolling deployment is a period with multiple versions, not an instantaneous replacement. The database, producers, consumers and cached clients may all run different code. An additive change is useful only if old readers tolerate it and the new writer does not destroy information they still need. Plan compatibility as a sequence with observable exit conditions.","id":"systems.compatibility","objective":"Use expand–migrate–contract changes while old and new Go processes coexist.","task":{"reading":{}},"title":"Evolve APIs, events and schemas across mixed deployments"},{"conceptTags":["systems.tenant-isolation"],"explanation":"A request can be authenticated and still read another tenant’s object. Authentication proves a principal; authorization decides whether that principal may perform this operation on this resource. Tenant isolation fails when one endpoint is careful but a cache key, bulk export or queued job forgets the same boundary. Treat tenant identity as part of the operation contract.","id":"systems.tenant-isolation","objective":"Carry a verified tenant identity into storage predicates, cache keys and background jobs.","task":{"reading":{}},"title":"Tenant isolation belongs in every access path"},{"conceptTags":["systems.observability"],"explanation":"A service can emit millions of log lines while providing no evidence about a failed business operation. Start with a question: is the checkout successful within its time budget, and where is the budget spent? Logs explain individual events, metrics describe distributions and rates, and traces connect sampled work across boundaries. They should share stable operation semantics without sharing every field.","id":"systems.observability","objective":"Connect structured logs, bounded metrics and traces to an explicit service objective.","task":{"reading":{}},"title":"Observe a Go use case without drowning in cardinality"},{"conceptTags":["systems.rpc-contracts"],"explanation":"Generated Go stubs remove repetitive transport code, not the need to design a distributed operation. A gRPC method can block, partially stream data, be retried or outlive its caller unless the application defines its lifetime. Treat protobuf fields as a versioned wire contract and the RPC method as a budgeted operation with explicit authorization and failure semantics.","id":"systems.rpc-contracts","objective":"Define deadlines, stream ownership, status mapping and compatible message evolution.","task":{"reading":{}},"title":"gRPC and Protobuf: generated methods still need an operational contract"},{"conceptTags":["systems.messaging-offsets"],"explanation":"A broker can redeliver messages after a consumer crash or partition reassignment. Processing records concurrently makes offset handling more subtle: finishing a later record does not prove that earlier records are durable. Track completion per partition and advance only across the contiguous successful prefix. The business effect needs its own deduplication or transaction protocol.","id":"systems.messaging-offsets","objective":"Separate message delivery, durable effects and partition-offset ownership.","task":{"reading":{}},"title":"Kafka-style consumers: commit only a contiguous completed prefix"},{"conceptTags":["systems.consistency-partitions"],"explanation":"A network partition can prevent replicas from coordinating. Whether a particular operation may proceed depends on the required consistency contract and the available authority, not on whether the service was written in Go or has a cache. Specify which reads may be stale, which writes require a leader or quorum, and what the caller sees when that requirement cannot be met.","id":"systems.consistency-partitions","objective":"Choose per-operation consistency and failure behavior instead of treating CAP as a product rating.","task":{"reading":{}},"title":"Consistency under partitions: explain an operation, not a slogan"}],"summary":"Transactions, outbox/inbox, sagas, compatible changes, tenant isolation and observability.","title":"Architecture: consistency and evolution","translationNote":"Work through ownership, durable state and failure recovery. Models distinguish in-memory behavior from the native infrastructure required in production."},{"id":"clean-code-production","lessons":[{"conceptTags":["clean-production.composition"],"explanation":"Dependency injection in Go is usually ordinary constructors and parameters. The important question is not which container library to use but who creates a shared client, who is allowed to close it and how partial startup is cleaned up. Keep wiring near main so a handler cannot silently allocate a new database pool or depend on a hidden global singleton.","id":"clean-production.composition","objective":"Construct dependencies once and make their ownership and shutdown order explicit.","task":{"reading":{}},"title":"A composition root makes lifetime and cleanup visible"},{"conceptTags":["clean-production.context-contracts"],"explanation":"Passing context.Context as the first parameter lets cancellation and deadlines cross a call boundary. It does not force the callee to stop, and it does not prove that a goroutine has exited. Context values are for request-scoped metadata that must cross API boundaries, not an alternative constructor or a hidden transport for required service dependencies.","id":"clean-production.context-contracts","objective":"Propagate request cancellation while giving detached work an explicit owner and deadline.","task":{"reading":{}},"title":"Context is a cancellation contract, not a bag of dependencies"},{"conceptTags":["clean-production.package-apis"],"explanation":"A repository with packages named controllers, managers and utils can still have no useful boundaries. Ask which behavior changes together and which caller is allowed to depend on it. Go import cycles are prohibited, but a cycle-free graph can still expose every storage struct and force unrelated features to change together. Test the public behavior of a capability, not its current arrangement of private helper calls.","id":"clean-production.package-apis","objective":"Use narrow consumer contracts and tests that make accidental coupling visible.","task":{"reading":{}},"title":"Package APIs should reveal their change boundary"},{"conceptTags":["clean-production.time-money"],"explanation":"An int64 does not tell the next engineer whether it represents milliseconds, Unix seconds, cents or token base units. A float64 cannot represent every decimal amount exactly. At API boundaries, define units, range, rounding and whether a missing field differs from zero. Inside the program, use types and constructors that make those contracts difficult to confuse.","id":"clean-production.time-money","objective":"Separate durations, instants and exact amounts instead of passing ambiguous numbers.","task":{"reading":{}},"title":"Time and money need units and presence in their types"}],"summary":"Composition roots, context ownership, package APIs and exact time/money contracts.","title":"Clean code: production contracts","translationNote":"Readable Go also needs explicit lifetime, units and failure contracts. These worked examples complement the foundational clean-code unit."},{"id":"patterns-creational","lessons":[{"conceptTags":["patterns.factory-method"],"explanation":"Vary product creation without duplicating the algorithm that uses it. The classic Factory Method lets an algorithm ask an overridable creation operation for a product. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.factory-method","objective":"Vary product creation without duplicating the algorithm that uses it.","task":{"reading":{}},"title":"Factory Method: supply the creation step"},{"conceptTags":["patterns.abstract-factory"],"explanation":"Create related products through one selected family. Abstract Factory selects a family of products that should work together. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.abstract-factory","objective":"Create related products through one selected family.","task":{"reading":{}},"title":"Abstract Factory: compatible product families"},{"conceptTags":["patterns.builder"],"explanation":"Represent staged construction without making invalid results usable. Builder separates assembly steps from the finished value. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.builder","objective":"Represent staged construction without making invalid results usable.","task":{"reading":{}},"title":"Builder: assemble then validate"},{"conceptTags":["patterns.prototype"],"explanation":"Choose shallow or deep copying according to ownership. Prototype creates an object from an existing configured object. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.prototype","objective":"Choose shallow or deep copying according to ownership.","task":{"reading":{}},"title":"Prototype: copy a useful starting value"},{"conceptTags":["patterns.singleton"],"explanation":"Understand one-instance intent and choose an explicit lifetime. Singleton controls access to one instance. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.singleton","objective":"Understand one-instance intent and choose an explicit lifetime.","task":{"reading":{}},"title":"Singleton: once does not mean global mutable state"}],"summary":"Factory Method, Abstract Factory, Builder, Prototype and Singleton.","title":"Patterns: creation","translationNote":"Classic intent, Go implementation: constructors, function values and composition instead of inheritance."},{"id":"patterns-structural","lessons":[{"conceptTags":["patterns.adapter"],"explanation":"Keep conversion details at the boundary that needs them. An adapter lets an existing implementation satisfy a different caller contract. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.adapter","objective":"Keep conversion details at the boundary that needs them.","task":{"reading":{}},"title":"Adapter: translate one contract into another"},{"conceptTags":["patterns.bridge"],"explanation":"Compose an abstraction with a separately variable implementation. Bridge separates an abstraction from its implementation so each can vary independently. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.bridge","objective":"Compose an abstraction with a separately variable implementation.","task":{"reading":{}},"title":"Bridge: two independent dimensions of variation"},{"conceptTags":["patterns.composite"],"explanation":"Define recursive behavior while guarding the shape of the structure. Composite exposes one operation on both individual values and groups. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.composite","objective":"Define recursive behavior while guarding the shape of the structure.","task":{"reading":{}},"title":"Composite: treat leaves and groups uniformly"},{"conceptTags":["patterns.decorator"],"explanation":"Wrap a small operation instead of constructing a type hierarchy. Decorator adds behavior around an object while retaining the interface clients already use. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.decorator","objective":"Wrap a small operation instead of constructing a type hierarchy.","task":{"reading":{}},"title":"Decorator: add behavior while preserving the contract"},{"conceptTags":["patterns.facade"],"explanation":"Simplify orchestration without pretending several effects are atomic. A facade offers a convenient operation over several lower-level components. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.facade","objective":"Simplify orchestration without pretending several effects are atomic.","task":{"reading":{}},"title":"Facade: one useful entry point over a subsystem"},{"conceptTags":["patterns.flyweight"],"explanation":"Separate reusable data from per-use context before optimizing memory. Flyweight shares intrinsic state across many logical objects while callers supply extrinsic context. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.flyweight","objective":"Separate reusable data from per-use context before optimizing memory.","task":{"reading":{}},"title":"Flyweight: share immutable intrinsic state"},{"conceptTags":["patterns.proxy"],"explanation":"Make caching or lazy access preserve the caller’s expectations. Proxy stands in for a real subject and controls access, for example with caching, authorization or lazy construction. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.proxy","objective":"Make caching or lazy access preserve the caller’s expectations.","task":{"reading":{}},"title":"Proxy: control access to an existing operation"}],"summary":"Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy.","title":"Patterns: composition","translationNote":"Follow data ownership and delegated calls. Wrappers should preserve the contracts their callers depend on."},{"id":"patterns-behavioral","lessons":[{"conceptTags":["patterns.strategy"],"explanation":"Pass interchangeable behavior through a function or small interface. Strategy isolates an algorithm that changes independently of its caller. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.strategy","objective":"Pass interchangeable behavior through a function or small interface.","task":{"reading":{}},"title":"Strategy: choose an algorithm explicitly"},{"conceptTags":["patterns.command"],"explanation":"Make actions queueable or reversible without claiming every effect can be undone. Command packages an operation and its receiver into a value that can be executed later. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.command","objective":"Make actions queueable or reversible without claiming every effect can be undone.","task":{"reading":{}},"title":"Command: represent an action as a value"},{"conceptTags":["patterns.chain"],"explanation":"Stop or delegate deliberately and make short-circuit order visible. A chain passes a request through handlers that can decide whether to continue. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.chain","objective":"Stop or delegate deliberately and make short-circuit order visible.","task":{"reading":{}},"title":"Chain of Responsibility: ordered handlers"},{"conceptTags":["patterns.iterator"],"explanation":"Use iter.Seq or a small Next API and honor early termination. Iterator gives callers sequential access without revealing collection internals. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.iterator","objective":"Use iter.Seq or a small Next API and honor early termination.","task":{"reading":{}},"title":"Iterator: yield values without exposing storage"},{"conceptTags":["patterns.mediator"],"explanation":"Let participants communicate through a focused coordinator. Mediator moves interaction rules out of a set of objects that otherwise know one another directly. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.mediator","objective":"Let participants communicate through a focused coordinator.","task":{"reading":{}},"title":"Mediator: centralize collaboration deliberately"},{"conceptTags":["patterns.memento"],"explanation":"Let the owner define what a valid snapshot contains. Memento stores state so its owner can restore a previous version without exposing editable internals to the caretaker. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.memento","objective":"Let the owner define what a valid snapshot contains.","task":{"reading":{}},"title":"Memento: retain a restorable snapshot"},{"conceptTags":["patterns.observer"],"explanation":"Keep notification lifetime and delivery semantics explicit. Observer lets interested listeners subscribe to changes without the subject knowing their concrete types. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.observer","objective":"Keep notification lifetime and delivery semantics explicit.","task":{"reading":{}},"title":"Observer: subscribe, notify and unsubscribe"},{"conceptTags":["patterns.state"],"explanation":"Represent legal transitions instead of scattered boolean combinations. State makes behavior depend on an explicit lifecycle state. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.state","objective":"Represent legal transitions instead of scattered boolean combinations.","task":{"reading":{}},"title":"State: behavior follows a valid lifecycle"},{"conceptTags":["patterns.template-method"],"explanation":"Adapt the inheritance-based intent using composition in Go. Template Method defines the order of an algorithm while allowing selected steps to vary. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.template-method","objective":"Adapt the inheritance-based intent using composition in Go.","task":{"reading":{}},"title":"Template Method: fixed workflow, supplied steps"},{"conceptTags":["patterns.visitor"],"explanation":"Understand the tradeoff between adding node types and adding operations. Visitor separates operations from a stable object structure using dispatch through the node type. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.visitor","objective":"Understand the tradeoff between adding node types and adding operations.","task":{"reading":{}},"title":"Visitor: new operations over a stable set of nodes"},{"conceptTags":["patterns.interpreter"],"explanation":"Model a grammar without treating arbitrary text as executable code. Interpreter represents a grammar with expression nodes and evaluates them against a context. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.interpreter","objective":"Model a grammar without treating arbitrary text as executable code.","task":{"reading":{}},"title":"Interpreter: evaluate a deliberately small language"}],"summary":"Eleven classic patterns, from Strategy and Command to State, Visitor and Interpreter.","title":"Patterns: behavior","translationNote":"Introduce machinery only when the variation exists. Each lesson includes a simpler alternative and the cost of the pattern."},{"id":"patterns-go","lessons":[{"conceptTags":["patterns.worker-pool"],"explanation":"Control active work instead of starting one goroutine for every input. A worker pool bounds the number of operations in progress. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.worker-pool","objective":"Control active work instead of starting one goroutine for every input.","task":{"reading":{}},"title":"Worker pool: bound simultaneous work"},{"conceptTags":["patterns.fan-in"],"explanation":"Coordinate multiple producers and one result stream. Fan-out spreads work across producers or workers; fan-in merges their results. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.fan-in","objective":"Coordinate multiple producers and one result stream.","task":{"reading":{}},"title":"Fan-out and fan-in: merge without assuming order"},{"conceptTags":["patterns.cancellation"],"explanation":"Make a producer stop when its consumer no longer needs results. Cancellation is a cooperative signal, not a forced goroutine kill. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.cancellation","objective":"Make a producer stop when its consumer no longer needs results.","task":{"reading":{}},"title":"Cancellation: propagate an exit path through every handoff"},{"conceptTags":["patterns.actor-owner"],"explanation":"Use one goroutine to own mutable state and define request completion. An actor-like owner serializes access to its state through messages. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.actor-owner","objective":"Use one goroutine to own mutable state and define request completion.","task":{"reading":{}},"title":"Single owner: serialize state through messages"},{"conceptTags":["patterns.retry"],"explanation":"Retry transient failures within one deadline without multiplying side effects. A retry repeats an operation that may already have succeeded remotely. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.retry","objective":"Retry transient failures within one deadline without multiplying side effects.","task":{"reading":{}},"title":"Retry: bounded attempts and idempotent effects"},{"conceptTags":["patterns.circuit-breaker"],"explanation":"Separate retry policy from failure isolation and a controlled recovery probe. A circuit breaker rejects calls after repeated failures, waits for a recovery interval, then permits a probe. Trace the worked Go example, then compare the benefit with the cost before applying this design to your own project.","id":"patterns.circuit-breaker","objective":"Separate retry policy from failure isolation and a controlled recovery probe.","task":{"reading":{}},"title":"Circuit breaker: stop calls while a dependency recovers"}],"summary":"Worker pools, fan-in, cancellation, ownership, retries and circuit breakers.","title":"Patterns: concurrent Go","translationNote":"Every goroutine needs an owner and an exit path. Production systems also need budgets, observability and failure tests."},{"id":"datastores","lessons":[{"conceptTags":["datastores.mongo-client"],"explanation":"MongoDB stores BSON documents and the Go driver manages discovery and pools for the deployment. A collection handle is not a new physical connection. Reuse a client across requests, model the fields the application owns, and keep network setup outside request-time package initialization.","id":"datastores.mongo-client","objective":"Connect with the Go v2 driver and separate construction, readiness, request work and cleanup.","task":{"reading":{}},"title":"MongoDB: one client, explicit deadlines and typed documents"},{"conceptTags":["datastores.mongo-indexes"],"explanation":"A query that is fast with ten documents may scan a large collection after real traffic arrives. Shape the filter, sort and returned fields around an actual use case, then inspect the execution plan and the documents examined. Indexes improve selected reads while adding write, memory and maintenance cost.","id":"datastores.mongo-indexes","objective":"Use explain evidence, tenant predicates and stable pagination rather than adding indexes blindly.","task":{"reading":{}},"title":"MongoDB: design the query and its compound index together"},{"conceptTags":["datastores.mongo-atomic"],"explanation":"Reading a document, changing a field in Go and writing it back leaves a window for another request to change the same value. Memory race detection cannot find that distributed lost update. Express the allowed transition in the database predicate and inspect whether the write actually matched.","id":"datastores.mongo-atomic","objective":"Prevent lost updates with atomic operators and optimistic version checks.","task":{"reading":{}},"title":"MongoDB: put the invariant in the write predicate"},{"conceptTags":["datastores.mongo-transactions"],"explanation":"A transaction can protect a multi-document invariant, but it adds coordination and can retry work. A callback that charges a card or sends email while updating documents can repeat an external effect. Keep the database transition inside the transaction and move external delivery behind an explicit durable boundary.","id":"datastores.mongo-transactions","objective":"Choose transaction boundaries, concerns and idempotency for ambiguous failures.","task":{"reading":{}},"title":"MongoDB transactions: retry database work, not external effects"},{"conceptTags":["datastores.mongo-cursors"],"explanation":"A cursor lets an application consume a result in batches; it is not permission to read the entire database without a budget. The query, projection, batch size, total limit and request deadline jointly determine network work and application memory. Check errors after iteration, not only when opening the cursor.","id":"datastores.mongo-cursors","objective":"Avoid loading an unbounded collection into application memory.","task":{"reading":{}},"title":"MongoDB cursors: bound the result and close the stream"},{"conceptTags":["datastores.mongo-load"],"explanation":"When every operation slows down, a larger pool can multiply pressure on the same database. Investigate where the deadline is spent: waiting in the application, selecting a server, checking out a connection, creating a socket or executing a query. Count all application instances and topology servers in the capacity model.","id":"datastores.mongo-load","objective":"Separate server selection, pool checkout, query time and application queueing.","task":{"reading":{}},"title":"MongoDB under load: budget waiting before enlarging the pool"},{"conceptTags":["datastores.redis-client"],"explanation":"Redis is often used as a low-latency data-structure service, but the network, client pool and command cost still exist. Create a shared client, keep a bounded operation context and distinguish redis.Nil from transport failures. A missing optional cache entry and an unavailable required store have different application contracts.","id":"datastores.redis-client","objective":"Configure go-redis deadlines, connection budgets and explicit cache-miss behavior.","task":{"reading":{}},"title":"Redis: share the client and distinguish a miss from an outage"},{"conceptTags":["datastores.redis-cache"],"explanation":"A cache duplicates another source of truth, so freshness and ownership must be explicit. Cache-aside reads can miss together, all query the origin and then repopulate the same key. TTL bounds one kind of staleness; it does not prevent a stampede or make a read-modify-write sequence correct.","id":"datastores.redis-cache","objective":"Design expiry, invalidation, negative caching and stampede control deliberately.","task":{"reading":{}},"title":"Redis cache-aside: TTLs do not solve concurrent fills"},{"conceptTags":["datastores.redis-pipeline"],"explanation":"Pipelining lets a client send multiple commands without waiting for every individual round trip. It can improve throughput for independent work, but it does not make the group indivisible. Large batches also retain commands and replies in memory and can worsen latency for other work.","id":"datastores.redis-pipeline","objective":"Bound command batches, inspect command errors and separate batching from atomicity.","task":{"reading":{}},"title":"Redis pipelines save round trips; they are not transactions"},{"conceptTags":["datastores.redis-coordination"],"explanation":"A counter with a timeout and a temporary ownership key look small, but concurrent requests and pauses expose their failure windows. Put dependent steps in one short atomic transition and distinguish an expired lease from a durable guarantee that only one worker can ever act.","id":"datastores.redis-coordination","objective":"Avoid split increment/expiry races and unsafe lock deletion.","task":{"reading":{}},"title":"Redis counters and leases need atomic transitions and ownership"},{"conceptTags":["datastores.redis-streams"],"explanation":"A consumer group tracks delivery and acknowledgment, not automatic exactly-once application effects. A worker may crash after updating another database but before XACK. Redelivery is useful recovery, so the handler must recognize an operation it has already applied.","id":"datastores.redis-streams","objective":"Understand consumer groups, pending entries, redelivery and bounded retention.","task":{"reading":{}},"title":"Redis Streams: acknowledge after the durable effect"},{"conceptTags":["datastores.redis-load"],"explanation":"Redis command latency can rise because of expensive commands, a hot key, big values, persistence work, network delay or waiting in the client. A low average hides queues and timeout bursts. Correlate request errors with server and client evidence before increasing goroutines or connection limits.","id":"datastores.redis-load","objective":"Inspect server latency and memory while bounding client work and retry amplification.","task":{"reading":{}},"title":"Redis under load: hot keys, memory pressure and ambiguous retries"}],"summary":"Clients, queries, atomic writes, caching, streams and behavior under load.","title":"Around Go: MongoDB and Redis","translationNote":"Read worked native-service examples here. Run them against an isolated development database on your own machine; these lessons do not add network sockets to the app sandbox."},{"id":"sql","lessons":[{"conceptTags":["sql.pool-lifetime"],"explanation":"sql.DB is a concurrency-safe pool handle, not a single database connection. Reuse it across the application and close it after its users drain. These lessons describe native Go services using a real driver; the app’s bounded WASI programs cannot open remote database sockets.","id":"sql.pool-lifetime","objective":"Configure database/sql as a shared pool and measure its actual pressure.","task":{"reading":{}},"title":"SQL: one pool, explicit capacity and observable waiting"},{"conceptTags":["sql.rows-and-context"],"explanation":"A successful QueryContext does not mean every row will decode successfully. Network and server errors can occur during iteration, and Scan can fail on a type or null mismatch. Decide whether partial results are meaningful; do not silently return a successful incomplete list.","id":"sql.rows-and-context","objective":"Write a cancellation-aware query loop without losing iteration failures.","task":{"reading":{}},"title":"SQL rows: close, check errors and bound the result"},{"conceptTags":["sql.transaction-owner"],"explanation":"Beginning a transaction does not attach later calls on sql.DB to it. The transaction handle owns a particular transactional connection. A helper that accidentally queries db instead of tx may see another state, escape rollback or wait for a second connection while holding the first.","id":"sql.transaction-owner","objective":"Place an atomic business transition inside one explicit transaction owner.","task":{"reading":{}},"title":"SQL transactions: every participating call uses the transaction"},{"conceptTags":["sql.isolation-and-locks"],"explanation":"A transaction can be atomic without providing the isolation an invariant needs. Two transactions may both read a condition as true and each make a different write that breaks the combined rule. Exact behavior depends on the database and isolation level; this lesson uses PostgreSQL terminology explicitly.","id":"sql.isolation-and-locks","objective":"Explain why atomic statements alone may not preserve a multi-row invariant.","task":{"reading":{}},"title":"SQL isolation and deadlocks: test the business invariant"},{"conceptTags":["sql.retry-and-idempotency"],"explanation":"Retrying the last failed SQL statement can be wrong when an earlier statement read stale state or the transaction is already aborted. A safe retry policy names the driver error, restarts the complete business unit when appropriate, stays within a total deadline and prevents repeated external effects.","id":"sql.retry-and-idempotency","objective":"Separate retryable transaction aborts from an ambiguous committed operation.","task":{"reading":{}},"title":"SQL retries: restart a safe transaction, reconcile an unknown result"}],"summary":"Shared pools, rows, transactions, isolation, deadlocks and retry-safe commands.","title":"Around Go: SQL services","translationNote":"Worked native Go and PostgreSQL examples. Use an isolated database in your own development environment; the app does not open database sockets."},{"id":"ai","lessons":[{"conceptTags":["ai.go-workflow"],"explanation":"Claude Code, Codex and Cursor can inspect files, propose patches and run available tools. Useful work still needs a concrete behavior and a way to check it. In this unit you guide an agent in your own repository. Ordinary native projects stay local. The separate Playground adds explicit, opt-in sharing with people and MCP clients; it never uploads an existing project automatically.","id":"ai.go-workflow","objective":"Turn an ambiguous coding request into a small, verifiable Go change.","task":{"reading":{}},"title":"A Go agent task starts with a contract and a failing example"},{"conceptTags":["ai.repository-guidance"],"explanation":"Durable guidance saves repeated explanation of layout, build commands and boundary rules. The supported discovery mechanisms differ between products and can change. Keep the repository facts stable, then consult the official documentation for how the installed tool discovers and scopes them.","id":"ai.repository-guidance","objective":"Write useful Go repository instructions without confusing context with permissions.","task":{"reading":{}},"title":"Repository guidance for Codex, Claude Code and Cursor"},{"conceptTags":["ai.verify-generated-go"],"explanation":"Generated source can look idiomatic while targeting the wrong driver major version or changing the public result. Compile against the selected module graph, inspect authoritative APIs and test the observable path. A plausible import name or confident explanation is not version evidence.","id":"ai.verify-generated-go","objective":"Catch invented APIs, unsafe concurrency and changed wire contracts in generated Go.","task":{"reading":{}},"title":"Verify generated Go against the real module and runtime"},{"conceptTags":["ai.trust-boundaries"],"explanation":"A source comment, dependency README, test log or fetched webpage can contain instructions written by someone else. Reading that material to solve a Go problem does not authorize its author to expand the task. Keep the user’s goal and trusted repository guidance separate from external diagnostic content.","id":"ai.trust-boundaries","objective":"Review commands, secrets and external writes when an agent consumes untrusted text.","task":{"reading":{}},"title":"Agent trust boundaries: repository text is input data"}],"summary":"Use Codex, Claude Code and Cursor with concrete contracts, repository context and meaningful checks.","title":"Around Go: coding agents","translationNote":"Ordinary projects stay local. The separate development Playground adds explicit opt-in MCP sharing; read the guide for local execution and provider boundaries."}]}