What you will learn in 100 Go Mistakes and How to Avoid Them
Chapter by chapter
Concepts explained in this book
- slicingSlicing is the Go operation that selects a half-open range of elements from an array or slice.
- backing arrayA backing array is the underlying array that stores the elements referenced by a Go slice.
- cache lineA cache line is the fixed-size unit of contiguous memory transferred between main memory and a processor cache.
- contractAn application programming interface is a defined set of operations and conventions through which software components interact.
- MapA map is a Go data structure that associates keys with values and requires keys to satisfy comparability rules.
- range loopA range loop is a Go loop construct that iterates over elements of an array, slice, map, string, pointer to an array, or receiving channel.
- channelA channel is a Go synchronization and communication mechanism through which goroutines send and receive typed values.
- stringA string is a Go value representing an immutable sequence of arbitrary bytes, conventionally containing UTF-8 text.
- data raceA data race is a concurrency error in which multiple executions access the same memory concurrently, at least one access is a write, and the accesses are not properly ordered or synchronized.
- garbage collectionGarbage collection is automatic runtime management that identifies and reclaims memory no longer reachable by a program.
- GOMAXPROCSruntime.GOMAXPROCS is a Go runtime function that sets or reports the maximum number of logical CPUs available for simultaneous Go execution.
- lockingA mutex is a synchronization primitive that provides mutual exclusion by allowing at most one execution to enter a protected section at a time.
- spatial localitySpatial locality is the tendency for memory locations near a recently accessed location to be accessed soon.
- profilingProfiling is the measurement of a program's runtime behavior and resource consumption to identify performance characteristics and bottlenecks.
- deferA defer statement schedules a function call to execute when the surrounding function returns, including during panic unwinding.
- capacitySlice capacity is the number of elements in the underlying array available to a Go slice from its starting position.
- concurrencyConcurrent execution is the overlapping progress of two or more threads or computations during the same time period.
- select statementA select statement is a Go control-flow construct that waits for and executes a communication operation from among channel cases.
- goroutineA goroutine is a lightweight independently executing function managed by the Go runtime.
- benchmarkA benchmark is a controlled measurement of software execution under specified workloads or inputs.
- parallelismParallel execution is the simultaneous execution of multiple instances of a task, typically on separate processing cores.
- slice lengthSlice length is the number of elements currently contained in a Go slice and available through its indices.
- performancePerformance is a measure of how efficiently a program performs its work, commonly including execution time and resource consumption.
- abstractionA software design technique that represents essential behavior or structure while hiding implementation details.
- referenceA pointer is a Go value that holds the memory address of another value or represents the absence of such an address.
- heapA memory heap is a region of runtime memory shared by goroutines for objects whose lifetimes cannot be confined to a stack frame.
- synchronizationSynchronization is the coordination of concurrent execution so that access to shared state occurs according to required ordering or exclusivity constraints.
- memory leakA memory leak is a failure to release memory or another managed resource after it is no longer needed.
- missing valueA null value is a database value representing the absence of a value rather than a value of the column's declared type.
- critical regionA critical section is a region of code that accesses shared state and must be protected from concurrent execution by other operations.
- error wrappingError wrapping is the practice of attaching contextual information to an error while preserving the underlying error for propagation and inspection.
- named result parameterA named result parameter is a Go function result parameter declared with an identifier that can be referenced within the function body and is initialized to its type's zero value.
- memory allocationMemory allocation is the process of reserving memory for data or runtime objects.
- slice copyA slice copy is the technique of copying selected elements into a separately allocated slice so the result does not retain the source array.
- cache missA cache miss occurs when requested data is not present in the relevant cache and must be obtained from a lower-level memory source.
- closureA closure is an anonymous function that retains references to variables from its surrounding lexical scope.
- execution context stackA call stack is the runtime-ordered sequence of active function calls through which control returns during execution.
- CPU cacheA CPU cache is small, fast hardware memory that stores recently accessed data and instructions near a processor core.
- task cancellationContext cancellation is the signaling of a context's invalidation so operations observing it can stop or abort their work.
- nil sliceA nil slice is a slice whose value is nil and whose length is zero without requiring an underlying allocation.
- pointer receiverA pointer receiver is a Go method receiver declared as a pointer, so the method can observe or modify the value referenced by that pointer.
- compute-boundA program whose performance is primarily limited by processor computation rather than input/output operations.
- heap profilingA heap profile is sampled data describing heap memory allocation and the current or historical state of heap usage.
- pprofnet/http/pprof is a Go standard-library package that exposes runtime profiling data through HTTP handlers.
- profilerA profiler is a software tool that collects and analyzes runtime measurements such as execution time, memory use, or resource consumption of an application.
- paddingPadding is the insertion of extra memory space between data fields to control their placement and alignment.
- cache placement policyA cache placement policy is a rule that determines where a fetched memory block is stored in a cache.
- genericsA programming-language feature that allows code and types to be parameterized over type parameters.
- runeA rune is Go's representation of a Unicode code point, implemented as an alias of int32.
- comparableComparable is a Go predeclared constraint satisfied by types whose values can be compared with == or !=.
- empty sliceAn empty slice is a Go slice whose length is zero, whether or not it has an allocated underlying array.
- value receiverA value receiver is a Go method receiver declared as a value, so the method operates on a copy of the receiver value.
- contextcontext.Context is the Go interface defining methods for retrieving deadlines, cancellation state, and propagated values.
- arrayA Go array is a fixed-length sequence of elements stored contiguously and serving as the backing storage for slices.
- thread poolA worker pool is a concurrency pattern that runs a fixed number of worker goroutines to process shared work or communicate through a common channel.
- busy-waiting loopA busy loop is a repeated polling loop that continuously checks a condition instead of blocking until the condition may have changed.
- packageA package is a Go unit of source organization and compilation that groups related declarations and controls dependencies between code units.
- performance optimizationA compiler optimization is a transformation that improves generated program code while preserving its required behavior.
- sync packageThe sync package is a Go standard-library package providing synchronization primitives for coordinating concurrent execution and protecting shared state.
- methodA method is a Go function associated with a receiver type and invoked on a value or pointer of that type.
- deadlockA deadlock is a state in which concurrent executions are permanently blocked because each is waiting for an event or resource that cannot become available.
- exported identifierAn exported element is a Go package declaration whose name begins with an uppercase letter and is accessible from other packages.
- instruction-level parallelismInstruction-level parallelism is a processor capability and execution technique that overlaps independent instructions within a sequence.
- %w error verbThe %w directive is a Go fmt formatting directive that records an operand as the underlying error of a returned formatted error.
- threadA thread is the smallest unit of execution that an operating system schedules within a process.
- context switchingContext switching is the act of suspending one execution context and resuming another on a processor or runtime worker.
- schedulerA scheduler is a runtime or operating-system component that selects executable threads or goroutines and assigns them processing resources.
- init functionAn init function is a special Go function that runs automatically to perform package initialization before program execution begins.
- cache partitioningCache partitioning is the organization of cache storage into distinct regions or sets that constrain where memory blocks can be placed.
- critical strideA critical stride is a memory-access spacing that repeatedly maps accesses to a restricted portion of a cache and wastes cache capacity.
- UTF-8UTF-8 is a variable-width Unicode character encoding in which characters are represented by sequences of one to four bytes.
- I/O-bound workAn I/O-bound workload is a workload whose execution time is primarily limited by input and output operations or an external system.
- bucketA bucket is an internal map storage unit that holds a fixed group of key-value entries and may be supplemented by overflow buckets.
- data hazardA data hazard is an instruction dependency in which one instruction requires a value produced or modified by another instruction.
- rate limitCPU throttling is the deliberate reduction of processor execution capacity in response to resource limits, thermal conditions, or power policies.
- sync.Condsync.Cond is a Go synchronization type that coordinates goroutines waiting for a condition associated with a locker.
- failureAn error value is a value representing an error condition that can be compared, returned, or propagated by a Go program.
- GoGo is a statically typed, compiled programming language designed for simplicity, concurrency, and efficient software development.
- package nameA package name is the identifier that names a software package and communicates the package's purpose to its users.
- cache replacement policyA cache replacement policy selects an existing cache line to evict when a new block must be stored in a full set.
- conflict missA conflict miss is a cache miss caused by multiple memory blocks competing for a restricted cache set.
- set-associative cacheA set-associative cache partitions cache lines into sets and restricts each memory block to one set while allowing placement among that set's lines.
- struct embeddingType embedding is a Go language feature that promotes the fields and methods of an embedded type into the embedding type's method set and selector space.
- race conditionA race condition is a concurrency defect in which program behavior depends on the timing or ordering of operations on shared state.
- couplingA software design technique that reduces direct dependencies between components so implementations can change independently.
- numerical overflowInteger overflow is the condition in which an integer operation produces a result outside the representable range of the integer type.
- bytesA byte is Go's alias for the unsigned 8-bit integer type uint8 and commonly represents one raw byte of data.
- false sharingFalse sharing is a performance problem in which independent variables occupy the same cache line, causing updates by different cores to invalidate one another's cached data.
- receiverA receiver is the parameter of a Go method that identifies the value or pointer on which the method operates.
- Closerio.Closer is a Go interface whose Close method releases or terminates an associated resource and returns an error.
- loopA classic for loop is a Go loop construct controlled by initialization, condition, and post statements rather than a range clause.
- immutable collectionImmutability is the property that a value or data object cannot be changed after creation.
- happens-before relationA happens-before relationship is a formal ordering relation in which one concurrent operation is guaranteed to occur before another for synchronization and memory-visibility purposes.
- branch predictionBranch prediction is a processor technique that forecasts the outcome of a conditional branch so subsequent instructions can be executed speculatively.
- control hazardA control hazard is an instruction-execution dependency caused by a conditional branch whose outcome determines subsequent instructions.
- instruction hazardAn instruction hazard is a condition that prevents or restricts the parallel execution of processor instructions.
- lambdaAn anonymous function is a function defined without an explicit name.
- float64float64 is Go's 64-bit floating-point type with an 11-bit exponent, a 52-bit mantissa, and a sign bit.
- closeA Close method terminates or releases an associated resource and reports whether that operation produced an error.
- rwmutexsync.RWMutex is a Go standard-library type that provides mutual exclusion with separate read and write locking modes.
- empty interfaceany is a predeclared Go alias for interface{} that can hold a value of any type.
- atomicityAn atomic operation is an indivisible operation that cannot be interrupted by competing accesses to the same data.
- time APIThe Go time API is the standard-library interface for obtaining, representing, and manipulating times and durations.
- Context.DoneThe Done method returns a channel that is closed when a context's cancellation or deadline signal occurs.
- BroadcastBroadcast is a sync.Cond method that wakes all goroutines currently waiting on the condition.
- condition variableA condition variable is a synchronization object that allows concurrent executions to wait for and announce the occurrence of a condition.
- waitWait is a sync.Cond method that releases its associated locker, blocks until notification, and reacquires the locker before returning.
- meanExecution time is the elapsed duration required for a computation or operation to complete.
- table-driven testA table-driven test organizes multiple test cases as data and applies shared testing logic to each case.
- errgrouperrgroup is a Go package for coordinating groups of goroutines with synchronization, error propagation, and context cancellation.
- race flagThe Go command-line flag that enables compiler instrumentation and runtime detection of data races.
- time.Aftertime.After is a Go standard-library function that returns a channel receiving a time value after a specified duration elapses.
- iteration orderMap iteration order is the sequence in which elements of a Go map are produced during iteration, which is not deterministic or insertion-preserving.
- full slice expressionA full slice expression is Go slice syntax with low, high, and maximum indices that sets the resulting slice capacity to max minus low.
- global variableA global variable is a variable whose scope allows access from multiple functions or locations within a package or program.
- inliningInlining is a compiler transformation that replaces a function call with the body of the called function.
- functional options patternThe functional options pattern configures an object by passing option functions, commonly through variadic arguments, to a constructor or setup function.
- merge sortA comparison-sorting algorithm that recursively divides a collection and merges sorted subcollections.
- parallel merge sortA merge sort implementation that processes independent sublists concurrently.
- parallelization thresholdA parallelization threshold is a workload-size boundary below which computation remains sequential instead of being split into concurrent tasks.
- data alignmentData alignment is the placement of data in memory at addresses satisfying the alignment requirements of the data type or hardware.
- field orderingField ordering is the arrangement of a struct's fields to control its memory layout and reduce unnecessary padding.
- shadowingA shadowed variable is a variable declaration that hides another variable with the same name in an enclosing scope.
- concatenationString concatenation is the operation of joining multiple strings into one string value.
- FP32float32 is Go's 32-bit floating-point type with an 8-bit exponent, a 23-bit mantissa, and a sign bit.
- conversion errorA conversion error is the numerical discrepancy introduced when converting a decimal or real value into a finite floating-point representation.
- exponentAn exponent is the multiplier component that determines the power applied to a floating-point mantissa.
- floating-point arithmeticA floating-point number is a finite-precision representation of a real value that uses a significand and exponent and may approximate real arithmetic.
- IEEE 754IEEE-754 is the standard defining representations and arithmetic behavior for floating-point numbers.
- mantissaA mantissa is the base or significand component of a floating-point representation.
- nanNaN is the IEEE-754 floating-point value representing an undefined or unrepresentable numerical result.
- precisionPrecision is the degree to which a numerical representation or computation preserves significant detail.
- scopeScope is the region of source code in which a variable name binding is valid and can be referenced.
- trajectoryAn execution tracer is a diagnostic tool that records runtime events such as scheduling, synchronization, and processor activity over time.
- connection poolingA database connection pool is a managed collection of reusable database connections that are allocated to operations and returned for later use.
- stop-the-world eventA stop-the-world period is an interval during which application execution is paused while runtime work such as garbage collection is performed.
- encapsulationEncapsulation is a software design technique that restricts direct access to state by placing it behind controlled operations or boundaries.
- channel capacityChannel capacity is the number of values a buffered Go channel can hold before a send blocks.
- heap escapeA heap escape is the allocation of a variable in the heap because it may be referenced after its function returns.
- stack frameA stack frame is the runtime record containing a function invocation's local state and associated execution information.
- Go memory modelThe Go memory model specifies the allowed behavior and ordering of memory operations in Go programs, including the effects of synchronization between goroutines.
- global queueA global queue is a scheduler queue shared among processor contexts for holding runnable goroutines.
- local queueA local queue is a scheduler queue associated with one processor context for holding runnable goroutines.
- preemptionPreemptive scheduling is a scheduling model in which the scheduler can interrupt an executing task and replace it with another task.
- work stealingWork stealing is a scheduling technique in which an underutilized processor obtains runnable tasks from another processor's queue.
- custom comparison methodA custom comparison method is programmer-defined comparison logic that checks the relevant fields or elements of values.
- exact-match accuracyThe equality operator == compares two Go values for equality according to their types and fields.
- reflect.DeepEqualreflect.DeepEqual is a Go function that recursively determines whether two values are deeply equal.
- reflectionReflection is the ability of a program to inspect and manipulate type and value information at runtime.
- substringA substring is a contiguous portion of a string obtained through a string operation such as slicing.
- brittle testA brittle test is a test whose result is unusually sensitive to incidental conditions such as timing, environment, or implementation details.
- dependency injectionDependency injection is a technique in which a component receives required dependencies from its caller rather than constructing or retrieving them internally.
- function typeA function type is a Go type whose values are functions with a specified parameter and result signature.
- mutable shared stateMutable shared state is data that can be modified and is accessible by multiple parts of a program or concurrent executions.
- stubA stub is a test double that supplies predetermined responses in place of a dependency.
- test doubleA substitute component used in testing in place of a real dependency or collaborator.
- test isolationTest isolation is the property that a test's outcome does not depend on state or execution effects from other tests.
- time.Nowtime.Now is a Go standard-library function that returns the current local time as a time.Time value.
- default caseA default case is a select or switch clause chosen when no other eligible case can be selected.
- uniform pseudo-random selectionUniform pseudo-random selection is a selection process that chooses among eligible alternatives with equal pseudo-random probability.
- side effectA side effect is an observable change or interaction caused by evaluating or executing code beyond producing its direct return value.
- strings.Builderstrings.Builder is a Go type for efficiently accumulating string data and producing a final string.
- io.Readerio.Reader is a Go interface for reading bytes from a data source.
- clockA wall clock is a clock that represents the current time of day and may jump forward or backward when synchronized.
- monotonic clockA monotonic clock is a time source that advances steadily for measuring elapsed durations without being adjusted backward by wall-clock changes.
- build tagA build tag is a Go source-selection constraint that controls whether a file is included in a build or test invocation.
- observer effectThe observer effect is a change in a system or measurement caused by the act of observing or measuring it.
- panicpanic is a Go built-in function or runtime state that stops normal execution and begins unwinding the current goroutine's call stack.
- errors.Aserrors.As is a Go standard-library function that recursively examines an error chain for an error assignable to a specified target type.
- iotestiotest is a Go standard-library package that provides utilities for testing readers and writers, including fault-injecting wrappers.
- field and method promotionField and method promotion is the Go behavior that makes members of an embedded type accessible through the containing type.
- error transformationError transformation is the conversion of an error into another error without preserving the original error for unwrapping.
- %v directiveThe %v formatting directive formats an error as text without preserving the original error for unwrapping.
- httptesthttptest is a Go standard-library package that provides facilities for testing HTTP clients and servers.
- type argumentA type argument is a concrete type supplied for a generic type parameter.
- template instantiationInstantiation is the compile-time process of applying concrete type arguments to a generic function or type.
- type constraintA constraint is a Go interface type that restricts the types permitted as generic type arguments.
- type inferenceType inference is the compile-time deduction of generic type arguments from a call or use context.
- underlying typeAn underlying type is the type that determines the representation and core identity shared by a defined Go type and its underlying type.
- union interfaceThe union operator | combines type terms in a Go generic constraint to permit multiple alternative types.
- octal literalAn octal integer is an integer literal represented in base 8, traditionally indicated in Go by a leading zero or explicitly by a 0o prefix.
- read-only modeA read-only configuration is configuration whose values can be retrieved but not updated through the exposed interface.
- sort.InterfaceThe Go sorting interface that defines collection length, element ordering, and element-swapping operations.
- naked returnA naked return is a Go return statement that omits result expressions and returns the current values of the function's named result parameters.
- deadlineA deadline is a time limit after which an operation or computation should be stopped or treated as expired.
- sql.Rowssql.Rows is a database/sql type that represents the result rows returned by a query.
- code pointA Unicode code point is a numeric value that identifies an abstract character or symbol in the Unicode standard.
- add methodThe Add method of sync.WaitGroup changes the number of concurrent operations that a WaitGroup waits to complete.
- WaitGroupsync.WaitGroup is a Go synchronization type that allows code to wait for a specified number of concurrent operations to complete.
- errors.Iserrors.Is is a Go standard-library function that reports whether an error chain contains a specified error value or matches it according to an Is method.
- sentinel errorAn error sentinel is a predefined error value representing a known condition that callers can compare against.
- errgroup.Grouperrgroup.Group is a type that coordinates a group of goroutines and records the first non-nil error returned by them.
- errgroup.Group.Goerrgroup.Group.Go starts a function returning an error in a new goroutine managed by an errgroup.Group.
- errgroup.Group.Waiterrgroup.Group.Wait blocks until all goroutines in an errgroup.Group complete and returns the first non-nil error, if any.
- errgroup.WithContexterrgroup.WithContext creates an errgroup.Group associated with a context and returns a derived context canceled when the group encounters an error or finishes waiting.
- timeoutA timeout is the termination or failure of an operation after it has waited longer than an allowed duration.
- Marshaler interfacejson.Marshaler is a Go interface for types that provide custom JSON encoding through a MarshalJSON method.
- cache hitA cache hit occurs when a requested memory location is found in the cache being checked.
- compulsory missA compulsory miss is a cache miss caused by the first access to a memory block that has not yet been loaded into the cache.
- data localityData locality is the tendency for related or recently accessed data to reside near one another in memory or storage.
- temporal localityTemporal locality is the tendency for a recently accessed memory location to be accessed again soon.
- fast-path optimizationA fast path is the execution path for a common case that can complete with relatively little work.
- call by valueA value copy is an independent value produced by copying another value rather than referring to the original value.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
