Common Go Errors

Go errors including nil pointer dereference, goroutine leaks, channel deadlocks, interface conversion, and concurrency issues.

76 errors documented with step-by-step fixes

Nil Pointer Dereference

runtime error: invalid memory address or nil pointer dereference

You are dereferencing a pointer that is nil. Check that the pointer is initialized before accessing its fields or methods.

Slice Bounds Out of Range

runtime error: index out of range [X] with length Y

You are accessing a slice or array index that exceeds its length. Verify the index is within bounds before accessing the element.

Assignment to Entry in Nil Map

assignment to entry in nil map

You are writing to a map that was declared but never initialized with make(). Initialize the map before assigning values.

Cannot Use X as Type Y

cannot use x (variable of type X) as type Y in argument to funcName

You are passing a value of the wrong type to a function or assigning it to an incompatible variable. Match the expected type or add a conversion.

Imported and Not Used

"fmt" imported and not used

You imported a package but never reference it in your code. Remove the unused import or use a blank identifier if you need the side effects.

Declared and Not Used

x declared and not used

You declared a variable but never used it. Remove the variable or use the blank identifier _ if you need to discard the value.

Missing Return at End of Function

missing return at end of function

Your function declares a return type but has a code path that does not return a value. Add a return statement to every possible exit path.

Cannot Range Over Expression

cannot range over x (variable of type T)

You are using range on a type that does not support iteration. Range only works on slices, arrays, maps, strings, and channels.

Goroutine Leak

goroutine leak detected: background goroutines still running after test completion

A goroutine is blocked forever because nothing will send to or receive from its channel, or its context was never cancelled. Always provide a way for goroutines to exit.

Race Condition Detected

WARNING: DATA RACE Read at 0x00c0000b4010 by goroutine 7 Previous write at 0x00c0000b4010 by goroutine 6

Two goroutines are accessing the same memory without synchronization. Use a mutex, channel, or atomic operation to protect shared data.

All Goroutines Are Asleep — Deadlock

fatal error: all goroutines are asleep - deadlock!

Every goroutine in your program is blocked waiting for something, so no progress can be made. Check for circular channel dependencies or missing sends.

Interface Conversion — Type Does Not Implement Interface

cannot use x (variable of type *MyStruct) as type MyInterface: *MyStruct does not implement MyInterface (missing Method method)

Your type does not implement all the methods required by the interface. Add the missing method with the correct signature.

Operation on Nil Channel

fatal error: all goroutines are asleep - deadlock! (caused by nil channel)

You are sending to or receiving from a channel that was never initialized with make(). Initialize the channel before using it.

Concurrent Map Read and Map Write

fatal error: concurrent map read and map write

Multiple goroutines are reading from and writing to the same map simultaneously. Use sync.RWMutex or sync.Map to protect concurrent map access.

Interface Conversion Panic — Type Assertion Failure

interface conversion: interface {} is string, not int

Your type assertion is wrong. The interface holds a different concrete type than you asserted. Use the two-value form of type assertion to check safely.

Multiple-Value in Single-Value Context

multiple-value os.Open() (value of type (*os.File, error)) used in single-value context

The function returns multiple values but you are only capturing one. Assign all return values or use the blank identifier to discard unwanted ones.

Undefined Variable

undefined: x

You are referencing a variable that has not been declared in the current scope. Check for typos or declare the variable before using it.

No New Variables on Left Side of :=

no new variables on left side of :=

All variables on the left side of := are already declared. Use = for assignment or introduce at least one new variable.

Cannot Convert Type

cannot convert x (variable of type string) to type int

You cannot directly convert between incompatible types like string and int. Use strconv.Atoi or strconv.Itoa for string-number conversions.

Too Many Arguments in Function Call

too many arguments in call to doSomething

You are passing more arguments than the function accepts. Check the function signature and remove the extra arguments.

Not Enough Arguments in Function Call

not enough arguments in call to doSomething

You are passing fewer arguments than the function requires. Check the function signature and provide all required arguments.

Too Many Return Values

too many return values have (int, error) want (int)

Your function returns more values than its signature declares. Update the return statement or the function signature to match.

No Return Values Expected

too many return values have (int) want ()

Your function does not declare any return type but has a return statement with a value. Either add a return type or remove the return value.

Error Return Value Not Checked

Error return value of `os.Remove` is not checked (errcheck)

You are ignoring an error return value from a function. Always check errors or explicitly discard them with the blank identifier.

Variable Shadowing in Inner Scope

declaration of "err" shadows declaration at outer scope (govet)

You are declaring a new variable with the same name as one in an outer scope, hiding the outer variable. Use = instead of := to reuse the outer variable.

Cannot Assign String to Byte Slice

cannot use s (variable of type string) as type []byte in assignment

Convert the string to a byte slice explicitly using []byte(s).

Cannot Access Unexported Field

user.name undefined (type User has no field or method name, but does have Name)

The field or method starts with a lowercase letter making it unexported. Capitalize the first letter to export it, or access it from within the same package.

Mixture of Field:Value and Value Initializers

mixture of field:value and value initializers

You are mixing named and positional field initialization in a struct literal. Use either all named fields or all positional values, not both.

Too Few Values in Struct Literal

too few values in struct literal of type Point

You are using positional struct initialization but not providing all fields. Supply all fields or switch to named field syntax.

Import Cycle Not Allowed

import cycle not allowed: package A imports package B which imports package A

Two packages depend on each other creating a circular dependency. Break the cycle by extracting shared types into a third package.

Initialization Loop

initialization loop: x refers to y, y refers to x

Two package-level variables depend on each other for initialization. Break the cycle by using a function or lazy initialization.

Defer in Loop — Resource Leak

possible resource leak, 'defer' is called in a 'for' loop (govet)

Deferred calls in a loop do not execute until the function returns, not at each loop iteration. Move the work into a separate function or close resources manually.

Loop Variable Captured by Closure

loop variable i captured by func literal (govet)

The goroutine or closure captures the loop variable by reference, so all iterations share the same variable. Create a local copy or pass it as a parameter.

Cannot Call Pointer Method on Value

cannot call pointer method Write on MyWriter

The method has a pointer receiver but you are calling it on a non-addressable value. Use a pointer to the value instead.

Unkeyed Fields in Struct Literal

composite literal uses unkeyed fields (govet)

Use field names in your struct literal instead of positional values. This makes the code resilient to struct changes and more readable.

JSON Unmarshal Requires a Pointer

json: Unmarshal(non-pointer main.Config)

Pass a pointer to json.Unmarshal, not a value. Use &config instead of config.

JSON Cannot Access Unexported Struct Fields

json: struct field name has no exported fields (silent failure — field is always empty)

The struct field starts with a lowercase letter so json.Marshal and Unmarshal cannot see it. Capitalize the field name and use json tags.

Append Result Not Assigned Back to Slice

result of append is not used (govet)

The append function returns a new slice but you are not assigning it back. Write s = append(s, item) to keep the result.

WaitGroup.Add Called Inside Goroutine

WaitGroup.Add called inside goroutine, causing race with Wait (govet)

Call wg.Add(1) before launching the goroutine, not inside it. Otherwise the main goroutine may call Wait before Add is executed.

Copying a Mutex Value

assignment copies lock value to x: sync.Mutex (govet)

You are copying a sync.Mutex by value which duplicates its internal state. Always pass mutexes by pointer or embed them in a struct passed by pointer.

Context Cancelled Error

context canceled

The context was cancelled before the operation completed. Check if your timeout is too short or if cancellation is triggered prematurely.

Context Deadline Exceeded

context deadline exceeded

The operation did not complete within the context's deadline. Increase the deadline or optimize the slow operation.

Constant Overflows Type

constant 256 overflows uint8

The constant value is too large for the target type. Use a larger type like uint16 or int64 to hold the value.

Mixed Named and Unnamed Parameters

mixed named and unnamed parameters

Function parameters must either all have names or all be unnamed. Add names to all parameters or remove all names.

Non-Boolean Used as Condition

non-boolean condition in if statement

Go requires explicit boolean expressions in if conditions. Unlike C, integers and pointers are not automatically treated as true/false.

Cannot Fallthrough in Type Switch

cannot fallthrough in type switch

Go does not allow fallthrough in type switch statements. Handle each type case independently or combine cases.

Break Is Not in a Loop or Switch

break is not in a loop, switch, or select

You are using break outside of a for loop, switch statement, or select statement. Move the break inside the correct control structure.

Label Defined and Not Used

label outerLoop defined and not used

You defined a label but never used it in a goto, break, or continue statement. Remove the unused label or add the corresponding jump statement.

Cannot Assign to Struct Field in Map

cannot assign to struct field m["key"].Name in map

Map values in Go are not addressable. You must copy the struct, modify it, and write it back to the map.

Send on Closed Channel

panic: send on closed channel

You are sending a value to a channel that has already been closed. Only the sender should close the channel, and only when no more values will be sent.

Close of Nil Channel

panic: close of nil channel

You are closing a channel that was never initialized. Ensure the channel is created with make() before closing it.

Negative Slice Index

runtime error: index out of range [-1]

Go does not support negative indexing like Python. Use len(s)-1 to access the last element.

Cannot Use Blank Identifier as Value

cannot use _ as value or type

The blank identifier _ is write-only. You cannot read from it or use it as a value in expressions.

HTTP Response Body Not Closed

response body must be closed (bodyclose linter)

Always close the HTTP response body with defer resp.Body.Close() after checking the error. Not closing it causes connection leaks.

String Indexing Returns Bytes Not Runes

unexpected byte value when indexing string with Unicode characters

Indexing a string with s[i] returns a byte, not a rune. Use a for range loop or convert to []rune for Unicode-safe character access.

Goroutine Refers to Enclosing Function Variable

goroutine may access variable after function returns, causing use-after-return

The goroutine outlives the function and accesses a local variable that may be garbage collected. Pass the variable as a parameter or ensure the function waits for the goroutine.

Duplicate Case in Switch

duplicate case 1 in switch previous case at line 5

You have the same value in two case clauses. Remove the duplicate or merge the case bodies.

Comparing Uncomparable Types

invalid operation: s1 == s2 (struct containing []int cannot be compared)

Structs containing slices, maps, or functions cannot be compared with == directly. Use reflect.DeepEqual or write a custom comparison.

Go Statement on Method Value With Nil Receiver

runtime error: invalid memory address or nil pointer dereference (in goroutine)

You called a method as a goroutine on a nil receiver. Check the receiver is not nil before spawning the goroutine.

Select With No Cases Blocks Forever

fatal error: all goroutines are asleep - deadlock! (caused by empty select)

An empty select{} blocks the goroutine forever. Use it only in main to keep the program alive, and ensure other goroutines can make progress.

Nil Interface vs Nil Concrete Type

unexpected: err != nil is true even though the underlying value is nil

An interface is nil only when both its type and value are nil. Wrapping a nil pointer in an interface creates a non-nil interface. Return nil directly instead of a typed nil pointer.

Recover Only Works in Deferred Functions

recover() returns nil because it was not called directly from a deferred function

recover() must be called directly inside a deferred function to catch panics. Calling it in a regular function or in a function called by defer does not work.

Map Iteration Order is Non-Deterministic

test failure: expected output order does not match (map iteration order is random)

Go maps have intentionally randomized iteration order. Sort the keys first if you need deterministic output.

Cannot Embed Unexported Interface

cannot embed unexported type somePackage.myInterface

You are trying to embed an unexported interface from another package. The interface must be exported (start with uppercase) to be embedded externally.

Iota Resets in Each Const Block

unexpected constant value: iota resets to 0 in new const block

iota resets to 0 at the beginning of each const block. Keep related constants in the same const block to maintain sequential values.

HTTP Handler Not Goroutine-Safe

race condition in HTTP handler: concurrent access to shared state

HTTP handlers run concurrently in separate goroutines. Shared state must be protected with a mutex or replaced with goroutine-safe alternatives.

Error Wrapping Uses Wrong Format Verb

non-wrapping format verb for fmt.Errorf. Use `%w` to format errors (errorlint)

Use %w instead of %v or %s in fmt.Errorf to properly wrap errors. Only %w allows errors.Is and errors.As to unwrap the chain.

Test Function Has Wrong Signature

wrong signature for TestFoo, must be: func TestFoo(t *testing.T)

Test functions must take exactly one parameter of type *testing.T and return nothing. Benchmark functions use *testing.B.

Unrecovered Panic in Goroutine

panic in goroutine crashes the entire program

A panic in a goroutine that is not recovered will crash the entire program. Add a deferred recover in goroutines that may panic.

Multiple Packages in Same Directory

found packages main (main.go) and utils (utils.go) in /path/to/dir

Each directory in Go can contain only one package (excluding test files with _test suffix). Move files to separate directories or use the same package name.

Module Not Found

cannot find module providing package github.com/foo/bar

The module is not in your go.mod file. Run go get github.com/foo/bar to add the dependency.

Cannot Embed Non-Interface Type in Interface

cannot embed non-interface type MyStruct in interface

Only interfaces can be embedded in other interfaces. If you want to compose struct types, embed them in a struct instead.

SQL Rows Not Closed — Connection Leak

sql: database/sql: Rows.Scan called without calling Rows.Close (or connection pool exhausted)

Always close sql.Rows with defer rows.Close() after checking the error. Not closing rows leaks database connections.

Sprintf Format Verb Mismatch

fmt.Sprintf format %d has arg of wrong type string (printf)

The format verb does not match the argument type. Use %s for strings, %d for integers, %f for floats, and %v for any type.

Modifying Map During Range Iteration

unpredictable behavior: new map entries may or may not appear during range iteration

Adding or deleting map entries during range iteration is allowed but has unpredictable results for new entries. Collect changes and apply them after the loop.

Misuse of unsafe.Pointer

possible misuse of unsafe.Pointer (govet)

unsafe.Pointer must follow specific conversion rules. Convert directly between pointer types in a single expression without intermediate uintptr storage.

Bugsly catches Go errors automatically

AI-powered error tracking that explains what went wrong and suggests fixes. Set up in 2 minutes.

Get Started Free