Go guides
Go guides: concurrency and testing, including the failure modes the compiler will not catch.
-
Fix Go "panic: runtime error: slice bounds out of range" — A High Bound Past Capacity, a Low Bound Past the High Bound, a Full Slice Expression Past Capacity, a String Past Its Length, and a Negative Bound
Go panics with slice bounds out of range when a slice expression's bounds break the rule for its form. For a simple slice expression on a slice, the bounds must satisfy 0 <= low <= high <= cap; on an array or a string the high bound is judged against the length instead. A full slice expression must satisfy 0 <= low <= high <= max <= cap. The panic text names the bounds that failed and the capacity or length they were judged against: [:5] with capacity 3, [3:1] with no limit named, [::5] with capacity 3, [:8] with length 5 for a string, and [-1:] for a negative low bound. A constant negative bound never reaches run time, because the compiler rejects it. This guide reproduces each shape exactly as Go 1.26.4 prints it and gives the bounds check that keeps each shape from reaching the panic.
-
Fix Go "panic: sync: negative WaitGroup counter" — Extra Done Calls, Add(-1) Past Zero, and the Add-Before-Go Rule
A sync.WaitGroup counter that goes negative panics with panic: sync: negative WaitGroup counter, and every route to it is a counting mismatch: one Done too many, an Add with a negative delta that overshoots zero, a Done on a WaitGroup that was never Added to, or a shared completion callback that fires twice. Done is exactly Add(-1), so the panic names Add in its stack trace even when your code only called Done. The ordering rules prevent the rest: a positive Add when the counter is zero must happen before Wait, Add calls belong before the go statement that creates the work, a reused WaitGroup takes new Add calls only after every previous Wait has returned, and WaitGroup.Go, available since Go 1.25, does the Add and the Done for you so the pair cannot drift apart. Each shape here is reproduced exactly as Go 1.26.4 prints it.
-
Fix Go "panic: runtime error: makeslice: len out of range" — Negative Length, Length Past Capacity, and Sizes That Overflow
A slice length that is negative, larger than its capacity, or so large that the runtime cannot allocate it makes make panic at the call itself: panic: runtime error: makeslice: len out of range when the length is the problem, and panic: runtime error: makeslice: cap out of range when the capacity is. The rule underneath both messages is one line: at every moment 0 <= len(s) <= cap(s), and a make that would break it never returns a slice at all. Constants that break the rule never even build — a constant negative length and constant length and capacity in the wrong order are compile errors — while the same values arriving in variables build fine and panic at run time. That split is why this panic survives testing: the numbers that trigger it usually come from input, from a count read off a wire, or from arithmetic that overflowed on the way to the make call. The fixes are all upstream of make: validate any length or capacity that came from outside the program, check size arithmetic for overflow before it reaches make, grow with append instead of pre-sizing from an untrusted number, and cap any preallocation hint at a sane bound. Each shape here is reproduced exactly as Go 1.26.4 prints it, with the check that prevents it.
-
Fix Go "panic: interface conversion" — A String Asserted to Int, a Nil Interface, a Type That Does Not Implement the Target Interface, and a Typed Nil
A single-value type assertion that fails panics in Go. Write x.(T) for x of interface type and a type T, and Go asserts the type of the value stored in x is identical to T, or, when T is an interface, that the stored type implements T. Hold, and you get the value stored in x. Fail, and you get a run-time panic instead. The message tells you what was stored and what you asked for: interface {} is string, not int when the concrete type is wrong, interface {} is nil, not int when the interface holds nothing, int is not fmt.Stringer: missing method String when the stored type lacks the method, and interface {} is *int, not int for a typed nil pointer. The comma-ok form of the same assertion does not panic; it returns the zero value for T and false. A type switch handles several possible stored types in one statement. Each shape here is reproduced exactly as Go 1.26.4 prints it, with the form that turns it into a value you can handle.
-
Fix Go "panic: runtime error: comparing uncomparable type []int" — Slice, Map and Function Values as Map Keys and in == Comparisons
Slice, map and function types are not comparable in Go: they can only be compared against nil. Written directly, comparing two slices or using a slice as a map key type is a compile error, so the panic in the title only arrives when the value reaches the comparison hidden inside an interface — two any values holding slices, a struct holding a slice compared through an interface, or an array or struct with interface fields. The map-key version of the same mistake prints a different panic, hash of unhashable type, when a slice, map or function value is inserted into or looked up in a map whose key type is an interface. Arrays and structs are comparable exactly when their elements and fields are, which is why the struct shape panics under its own name. The fixes replace the comparison or the key, never the panic: slices.Equal and maps.Equal for contents, reflect.DeepEqual with its nil-versus-empty distinction kept in view, and a comparable key — an array instead of a slice, a string form, an ID, or a struct of comparable fields — where a map key is what the code actually needed. Each shape here is reproduced exactly as Go 1.26.4 prints it, split into the shapes the compiler stops and the shapes that survive to run time.
-
Fix Go "panic: close of nil channel" — the Unmade Channel, and How Nil Channels Block, Disable Select Cases, and Panic on Close
panic: close of nil channel means the channel variable was never made: a var declaration, a struct field nobody assigned, or a constructor that returned the declared variable instead of make(chan T). The same nil value explains the rest of the family: a send on a nil channel blocks forever, a receive from a nil channel blocks forever, and a select case on a nil channel is never ready, which is a bug when it is accidental and the standard off switch when it is deliberate. Closing is different: close of a nil channel panics instead of blocking, and close of a made channel is how the sender signals that no more values will be sent. Each shape here is reproduced exactly as Go 1.26.4 prints it, including the contrast that keeps the three states separate: receive from a closed channel returns at once with the zero value and ok set to false, while receive from a nil channel never returns at all.
-
Fix Go "panic: close of closed channel" — A Second Close, a Nil Channel, and the Receives That Stay Safe After Close
Closing a channel that is already closed panics in Go. Call close(ch) and Go records that no more values will be sent on ch. Call it a second time and the program dies with panic: close of closed channel. Call it on a nil channel and the message changes by one word: panic: close of nil channel. Neither panic comes from receiving. A receive from a closed channel never panics at all: it drains any values still buffered, then returns the zero value with ok set to false, and a range loop over the channel ends on its own. The fixes follow from who owns the close. Only the sender closes, and it closes exactly once. Where several goroutines can trigger the close, a sync.Once guard makes the first call the only one that runs. Each shape here is reproduced exactly as Go 1.26.4 prints it, with the pattern that prevents it.
-
Fix Go "panic: send on closed channel" — Close of Closed and Nil Channels, Receiving From a Closed Channel, and select
Go panics with send on closed channel when a program sends on a channel after close has been called on it: a sender that outlives the close, a loop that closes inside its own body and sends on the next pass, and a select whose send case names a closed channel all meet the same rule. Closing a channel twice panics with close of closed channel, and closing a nil channel panics with close of nil channel. Receiving runs the other way: a receive from a closed channel returns the values sent before the close and then the zero value at once, with the two-value form reporting ok as false. This guide reproduces each shape exactly as Go 1.26.4 prints it and gives the single-closer ownership, the done channel, and the ok check that keep each shape from reaching the panic.
-
Fix Go "panic: runtime error: invalid memory address or nil pointer dereference" — Nil Receivers, Returned Nil Pointers, and Typed Nil Interfaces
Go panics with runtime error: invalid memory address or nil pointer dereference when a program uses a pointer whose value is nil: reading or writing through it, taking a field of the value it would point to, or calling a method that uses its receiver. A declared but never assigned pointer holds nil, a function that returns nil on one path hands the panic to its caller, a pointer field left at its zero value breaks a chain of field accesses one link in, and a typed nil pointer stored in an interface passes a plain nil check and panics later. This guide reproduces each shape exactly as Go 1.26.4 prints it and gives the allocation, the nil check, and the nil-safe method that keep each shape from reaching the dereference.
-
Fix Go "panic: runtime error: integer divide by zero" — Variable Divisors, the Constant-Divisor Compile Error, Modulo, and the Empty Average
Go panics with integer divide by zero when an integer division or remainder runs with a divisor that is zero at run time: a variable divisor that arrives as zero, a length used as a divisor on an empty slice, and an unsigned divisor all print the same panic text. A divisor that is a constant zero never reaches run time, because the compiler rejects it with invalid operation: division by zero. Floating-point division by zero does not print this panic in Go 1.26.4: it prints +Inf, -Inf, or NaN. This guide reproduces each shape exactly as Go 1.26.4 prints it and gives the divisor guard and the empty-input check that keep each shape from reaching the panic.
-
Fix Go "panic: runtime error: index out of range" — Slice, Array, String, and Slice-Bounds Panics
Go panics with runtime error: index out of range when a program indexes an array, slice, or string outside 0 <= x < len(a), and with slice bounds out of range when a slice expression's low, high, or max bound leaves its allowed range, because the valid index set is set by length for indexing and by capacity for slicing, a constant index that is out of range for an array or a constant string is a compile error instead of a panic, and an index equal to the length is already out. This guide reproduces the panic family exactly as Go 1.26.4 prints it — too-large, negative, and equal-to-length indices, string indexing, simple and three-index slice bounds, and the off-by-one loop — and gives the bounds check, the range loop, and the len/cap reasoning that keep each shape in range.
-
Fix Go "assignment to entry in nil map" Panic — Declared Maps, Struct Fields, and Nested Maps
Go compiles a program that assigns to a nil map without a word of complaint and then panics at run time with assignment to entry in nil map, because a map declared with var, a map field inside a zero-value struct, a map a helper returned as nil, and the inner map of a nested map all start life as nil, and a nil map accepts every read — lookup, len, range, delete — while refusing every write. This guide reproduces that panic exactly as Go 1.26.4 prints it and works through the shapes that produce it: the declared-but-never-made map, the struct field nobody initialized, the map made only on one branch, the nil a function hands back to a caller that writes to it, and the inner map of a made outer map — ending with the contrasts that separate this panic from its look-alikes: reading a nil map is safe and returns zero values, and appending to a nil slice works, so the defect is specific to writing into a map that was never made.
-
Fix Go "fatal error: all goroutines are asleep - deadlock!" — Unbuffered Channels, Nil Channels, select, and Unclosed Ranges
Go compiles a program whose only goroutine blocks forever on a channel operation and then the runtime kills it with fatal error: all goroutines are asleep - deadlock!, because a receive on an unbuffered channel with no sender, a send with no receiver, an empty select, a receive from a nil channel, a range over a channel nobody closes, and a second receive after a worker sent exactly once all leave every goroutine blocked with nothing left that can wake any of them. This guide reproduces that fatal error exactly as Go 1.26.4 prints it and works through the shapes that produce it — ending with the contrasts that separate a deadlock from a merely blocked program: a goroutine waiting on a timer can still wake, so the detector stays silent, and the fatal error is not a panic, so recover cannot catch it.
-
Fix Go "Undefined: ..." Compile Errors — Identifiers, Scope, and Package Qualifiers
Go prints undefined: name when a name in the code has no declaration in scope at the point where it is used, and the name after the colon is the whole diagnosis. This guide reproduces that message exactly as Go 1.26.4 prints it and works through the shapes that produce it: a name that was never declared, a typo or a change of letter case — Go identifiers are case-sensitive, and the first letter also decides whether a package member is exported — a local variable used before its declaration, because a local variable's scope begins at the end of its declaration statement, a variable used after the block, if, or for statement that declared it has ended, a missing package qualifier such as Println without fmt., a missing import, which makes the package name itself undefined, and a renamed import used under its old name — ending with the contrasts that separate this error from its look-alikes: a function may call another function declared later in the file because package-level scope covers the whole package, and an inner declaration that shadows an outer name compiles without any message at all.
-
Fix Go "Too Many Arguments" and "Not Enough Arguments in Call" — Call Arity, Variadic Functions, and the Spread Operator
Go counts the arguments at every call against the function's parameter list and refuses to compile when the counts differ, printing the numbers it found and the numbers it wanted. This guide reproduces those messages exactly as Go 1.26.4 prints them and works through the shapes that produce them: an extra argument to an ordinary function, a missing argument, an argument passed to a function that takes none, an extra argument to a method or to a function value, a second argument to the built-in len, a variadic function called with no arguments for its fixed parameter, a slice passed to a variadic function without the spread operator, and the spread operator used on a function that is not variadic — ending with the contrasts that separate these errors from their look-alikes: a variadic function takes zero arguments for its variadic parameter, a slice spreads only with ..., and a call that passes another call's return values directly is the one exception to the count.
-
Fix Go "No Required Module Provides Package" — Module Resolution, Typos, Cycles, and the Replace Fix
Go refuses to build when an import names a package no module provides, printing 'no required module provides package' with the command that would add it. This guide reproduces those messages exactly as Go 1.26.4 prints them and works through the shapes that produce them: a missing go.mod file, an imported package with no requirement, a misspelled standard package, an import cycle between two local packages, and a lookup switched off by GOPROXY — ending with the fixes that belong to each shape: go mod tidy, go get, a replace directive to a local module, and the subpackage that needs no requirement at all.
-
Fix Go "missing return at end of function" — Return Paths, Named Results, and Branch Coverage
Go prints missing return when a function that declares result parameters can reach the end of its body without returning a value, and the position it prints is the function's closing brace. This guide reproduces that message exactly as Go 1.26.4 prints it and works through the shapes that produce it: a function with result parameters and no return at all, an if/else where one branch returns and the other falls through, a switch whose cases return but which has no default and no return after it, a return that sits only inside a for loop body, named result parameters where a bare return is legal on one path and a missing return is the defect on another, and a return hidden inside a nested block or an if initializer — ending with the contrasts that separate this error from its look-alikes: a function with no result parameters needs no return, a bare return with named results is legal, and Go has no implicit return at the end of a function.
-
Fix Go "Cannot Assign To ..." Compile Errors — Addressability, Map Values, Constants, and Call Results
Go refuses an assignment when the left-hand side has nowhere to store a value, printing 'cannot assign to' with the reason in parentheses. This guide reproduces those messages exactly as Go 1.26.4 prints them and works through the shapes that produce them: a field of a struct stored in a map, a constant, a function call's return value, a field of a composite literal, a character of a string, a field of a call's return value, a pointer method called on a map value, and a conversion or built-in call used as a target — ending with the contrasts that separate these errors from their look-alikes: a map index itself is a legal target, a map index increments fine, and a slice element or a dereferenced pointer takes an assignment.
-
Fix Go "No New Variables on Left Side of :=" — Redeclaration, Scope, and Shadowing
Go refuses a short variable declaration when every non-blank name on its left side already exists in the same scope, and it prints one sentence for the refusal: no new variables on left side of :=. This guide reproduces that sentence exactly as Go 1.26.4 prints it, states the redeclaration rule behind it — a short declaration may redeclare a variable only in a multi-variable form, only when the earlier declaration stands in the same block with the same type, and only when at least one non-blank variable on the left side is new — and works through the cases that decide real code: the plain assignment fix and the two ways assignment itself fails, the mixed form that redeclares an error variable beside a new result, the blank identifier, which never counts as new, a repeated name on the left side, and the scope boundary where the same spelling stops being a redeclaration and becomes a new variable instead — an outer-block or package-level name, an inner block, and the if, for, and switch initializers — ending with the shadowing trap, where an inner := takes the writes and the outer variable keeps its old value, and the package-level :=, which is a syntax error rather than a declaration at all.
-
Fix Go "Declared and Not Used" and "Imported and Not Used" Compile Errors
Two Go compile errors stop a build over code that harms nothing at run time: a local variable that is declared and never read, and an import that no identifier in the file ever names. This guide reproduces both errors exactly as Go 1.26.4 prints them — declared and not used: x, and "fmt" imported and not used — states the precise scope of each rule, and separates the cases that look alike but are not: assignment is not a use, while printing, passing, comparing, returning, incrementing and compound assignment all are; function parameters, named results, package-level declarations, struct fields and constants sit outside the variable rule entirely. It covers the blank identifier as the deliberate discard, its limits — it cannot rescue an import — the blank import form reserved for side-effect imports, multi-value declarations where only one value is wanted, variables declared in if and for headers, and the fixes ranked in the order to reach for them: use the value, remove the declaration, blank-assign only when the discard is the intent.
-
Fix Go "Cannot Use ... As ..." Type Errors — Assignability, Conversions, and Untyped Constants
Go assigns a value to a differently typed variable only when the language's assignability rule allows it, and every refusal arrives in one sentence: cannot use X as T value in a named place. This guide reproduces that sentence exactly as Go 1.26.4 prints it — for an untyped string constant given to an int, an int variable given to a string, a struct value, and the same refusal in an assignment, a call argument, and a return statement — states the assignability rule behind it (identical types, identical underlying types with at least one side unnamed, interface satisfaction, nil, and representable untyped constants), and works through the cases that decide real code: two named types over one underlying type, which are not assignable to each other; untyped constants, which pass at 3.0 and fail at 3.9 with a truncated note and at 300 into an int8 with an overflows note; the absence of implicit numeric conversion, even from int64 to int; explicit conversions, including the string(65) trap that yields one rune instead of digits; slice invariance, where []int is not []any; and interface failures that name the missing method.
-
Fix Go "Assignment Mismatch" and "Multiple-Value in Single-Value Context" Errors
Go functions return several values at once, and the compiler counts both sides of every assignment that receives them. This guide reproduces the two counting errors exactly as Go 1.26.4 prints them — assignment mismatch: 1 variable but pair returns 2 values, and multiple-value pair() in single-value context — states the tuple-assignment rule behind them (a multi-valued operation fills several variables only when it stands alone on the right side), and separates the places that look alike but follow different rules: the pass-through call f(g()), the return pass-through, a call used as a statement, and the three built-in operations — map index, type assertion, channel receive — that yield one value or two depending on how many variables receive them. It covers the mixed-list trap, where a two-value call beside another expression counts as one right-hand entry, the neighboring count checks with different messages (call arguments and return statements), and the fixes in order: bind every value, blank the ones that are unwanted on purpose, or pass the values through untouched.
-
Go Structs and Interfaces — Grouping Data and the Method Set That Defines Behavior
Go structs and interfaces: a Point struct prints (3,4) through its String method, a Rect satisfies the Shaper interface with no implements declaration and prints area=30, and an interface variable holding a Rect prints iface area=6. The same guide shows a pointer receiver changing a Rect from 2, 3 to 20, 30 while a value receiver leaves it alone, a struct copy changing only the copy, and an interface holding a nil pointer reporting isNil=false.
-
Go Slices and Maps — Append, Length, Capacity, and Lookup
The two containers every Go program uses: a slice that starts as 1, 2, 3, grows to len 5 cap 6 with append, and a map that gains a key, loses one, and answers a missing key with the comma-ok idiom. One program prints len 5 cap 6 s [1 2 3 4 5] and bo present: false value: 0.
-
Finding a Leaked Goroutine with Go 1.27's goroutineleak Profile
A goroutine blocked on a channel receive forever is a leak, and Go 1.27 made the goroutineleak profile generally available to find it. This walkthrough writes the leak, captures the profile with runtime/pprof, and reads it with go tool pprof: 1 leaked goroutine, parked in runtime.gopark via chanrecv, created by main.main.func1. The fixed program closes the channel and its profile shows 0 leaked goroutines..
-
Testing Cancellation with Go's synctest Bubble: 5 Seconds in 0.00
A 5-second deadline fires at exactly 5 seconds of virtual time and 0.00 seconds of real time inside a synctest bubble. This guide tests an errgroup pool's cancellation deterministically, explains what the bubble does and does not fake, and shows the race-detector sanity check on the same pool.
-
Go errgroup Worker Pool: The Race the Compiler Won't Catch
Build a bounded errgroup worker pool in Go, watch the race detector fail it with five data races, fix it with one mutex, and learn the SetLimit ceiling, the cancellation timing, and the deadlock trap — every result run.