go Errors

129 error patterns

go3 fixes

Generic type constraint not satisfied

cannot use.*as type parameter.*does not satisfy

  • Implement required interface methods on type
  • Change constraint to broader interface
go3 fixes

Type not comparable for generic constraint

comparable.*cannot be compared

  • Ensure type has no slice/map/func fields
  • Use comparable constraint explicitly
go3 fixes

Go type inference failure

cannot infer.*type parameter

  • Provide explicit type arguments
  • Add type annotation to variable
go3 fixes

Context cancelled or deadline exceeded

context canceled|context deadline exceeded

  • Check ctx.Err() before expensive operations
  • Increase context timeout
go3 fixes

Background context misuse in handler

context\.Background.*should not be used in.*handler

  • Use request context r.Context()
  • Derive child context from incoming request
go3 fixes

errors.Is comparison failure

errors\.Is.*target.*does not match

  • Use sentinel error variables for comparison
  • Implement Is() method on custom error
go3 fixes

errors.As nil pointer target

errors\.As.*target must be a non-nil pointer

  • Pass pointer to error variable
  • Initialize target variable before As call
go3 fixes

Multiple %w verbs in Errorf (pre-1.20)

fmt\.Errorf.*%w.*multiple.*not supported

  • Upgrade to Go 1.20+ for multiple %w
  • Use single %w with joined error message
go3 fixes

Goroutine leak detected

goroutine leak|leaked goroutine

  • Use context cancellation to signal goroutines
  • Close channels when done producing
go3 fixes

Goroutine deadlock

all goroutines are asleep.*deadlock

  • Ensure channel has reader before writing
  • Use buffered channels appropriately
go3 fixes

Semaphore acquire context expired

semaphore.*acquire.*context done

  • Increase semaphore weight capacity
  • Add timeout to context
go3 fixes

Errgroup child context cancelled

errgroup.*context canceled.*child

  • Handle context cancellation in goroutines
  • Use errgroup.WithContext for derived ctx
go3 fixes

Reflect call on zero Value

reflect.*call of.*on zero Value

  • Check IsValid() before calling methods
  • Verify pointer is non-nil before Elem()
go3 fixes

Reflect set on unaddressable value

reflect\.Value\.Set using unaddressable value

  • Pass pointer to reflect.ValueOf
  • Use .Elem() to get addressable value
go3 fixes

Reflect kind vs type confusion

reflect.*Kind.*struct.*not.*interface

  • Use .Kind() for category, .Type() for exact type
  • Check Kind == reflect.Struct before field access
go3 fixes

Reflect struct tag on unexported field

struct field.*tag.*not exported

  • Capitalize field name to export it
  • Use reflect with exported fields only
go3 fixes

Cgo C header/library not found

cgo.*C header.*not found|cannot find -l

  • Install development headers package
  • Set CGO_CFLAGS/CGO_LDFLAGS paths
go3 fixes

Cgo undefined symbol

cgo.*undefined reference to

  • Link required library with #cgo LDFLAGS: -l
  • Verify C function signature matches
go3 fixes

Cgo cannot determine C name kind

could not determine kind of name for.*cgo

  • Fix C header syntax errors
  • Ensure C.name matches C declaration
go3 fixes

Go mod replace target not found

go mod.*replace directive.*not found

  • Verify local path in replace directive
  • Use relative path from module root
go3 fixes

Go private module access denied

go.*private.*repository.*403|GONOSUMCHECK|GOPRIVATE

  • Set GOPRIVATE env for private repos
  • Configure .netrc for authentication
go3 fixes

Go vendor inconsistency

go mod vendor.*inconsistent vendoring

  • Run go mod vendor to resync
  • Delete vendor/ and regenerate
go3 fixes

Data race detected by race detector

go test.*race.*data race detected

  • Add mutex protection for shared state
  • Use sync/atomic for simple values
go3 fixes

t.Setenv in parallel test

testing.*parallel.*cannot use t\.Setenv

  • Remove t.Parallel() if env vars needed
  • Use separate env management for parallel tests
go3 fixes

Benchmark results unstable

benchmark.*too few iterations.*unstable

  • Reset timer with b.ResetTimer() after setup
  • Use b.StopTimer/StartTimer for non-measured work
go3 fixes

Fuzz corpus unmarshal failure

fuzz.*corpus.*failed to unmarshal

  • Fix corpus file format
  • Clear testdata/fuzz/ and regenerate
go3 fixes

gRPC-Go connection refused

grpc.*rpc error.*code = Unavailable.*connection refused

  • Verify server is running on target address
  • Use grpc.WithTransportCredentials(insecure) for no-TLS
go3 fixes

gRPC-Go deadline exceeded

grpc.*rpc error.*code = DeadlineExceeded

  • Set longer deadline with context.WithTimeout
  • Optimize server-side processing
go3 fixes

gRPC-Go interceptor panic

grpc.*unary interceptor.*panic

  • Add recovery middleware interceptor
  • Use grpc_recovery interceptor
go3 fixes

gRPC-Go metadata not in context

grpc.*metadata.*not found in context

  • Use metadata.FromIncomingContext(ctx)
  • Verify client sends metadata with ctx
go3 fixes

gRPC-Go stream transport closing

grpc.*stream.*SendMsg.*transport closing

  • Handle stream context cancellation
  • Implement graceful stream shutdown
go3 fixes

GORM record not found

gorm.*record not found

  • Check errors.Is(err, gorm.ErrRecordNotFound)
  • Use Find() instead of First() for optional
go3 fixes

GORM Preload relation not found

gorm.*Preload.*unsupported relations

  • Verify relation name matches struct field name
  • Use correct association tag (foreignKey, references)
go3 fixes

GORM association foreign key missing

gorm.*invalid association.*no.*foreign key

  • Add gorm:"foreignKey:" struct tag
  • Define FK field on the related model
go3 fixes

GORM transaction reuse after commit

gorm.*transaction.*already committed or rolled back

  • Don't reuse tx after Commit/Rollback
  • Create new transaction for subsequent ops
go3 fixes

Go type assertion failure

cannot use.*\(.*type\).*as.*in assignment

  • Use comma-ok pattern for safe assertion
  • Check interface compatibility
go3 fixes

Nil interface conversion panic

interface conversion.*nil.*not.*interface

  • Check for nil before type assertion
  • Use comma-ok idiom: v, ok := x.(T)
go3 fixes

Indexing unsupported type

invalid operation.*type.*does not support indexing

  • Verify type is slice/array/map/string
  • Cast interface to concrete type first
go3 fixes

Cannot range over generic with no core type

cannot range over.*has no core type

  • Add ~[]T or ~map constraint to type parameter
  • Use explicit iteration method
go3 fixes

Struct literal unkeyed fields warning

composite literal uses unkeyed fields

  • Use field names in struct literal
  • Add field: value syntax
go3 fixes

Go module version mismatch

go.*module.*requires go \d+.*but.*module is go

  • Update go directive in go.mod
  • Upgrade Go toolchain version
go3 fixes

gRPC-Go max concurrent streams exceeded

grpc.*server.*too many.*concurrent streams

  • Increase MaxConcurrentStreams in server options
  • Implement client-side stream pooling
go3 fixes

GORM unique constraint violation

gorm.*duplicate key value violates unique constraint

  • Use Clauses(clause.OnConflict{}) for upsert
  • Check existence before insert
go3 fixes

Concurrent map access without sync

sync\.Map.*concurrent.*fatal

  • Use sync.Map for concurrent access
  • Protect map with sync.RWMutex
go3 fixes

Send on closed channel panic

send on closed channel

  • Use sync.Once to close channel once
  • Check channel with select before send
go3 fixes

Slice bounds out of range

slice bounds out of range

  • Check len() before slicing
  • Use min(requested, len) for bounds
go3 fixes

Generic function needs instantiation

cannot use.*generic function.*without instantiation

  • Provide type arguments: fn[Type]()
  • Let compiler infer from arguments
go3 fixes

Go test timeout exceeded

go test.*timeout.*exceeded

  • Increase timeout with -timeout flag
  • Optimize slow test or use t.Skip
go3 fixes

Cgo passing Go pointer to C

cgo.*Go pointer.*to C.*not allowed

  • Copy data to C-allocated memory
  • Use C.CBytes/C.CString for conversion
go3 fixes

Reflect NumField on non-struct

reflect.*NumField.*non-struct type

  • Check Kind() == reflect.Struct first
  • Unwrap pointer with Elem() before NumField
go3 fixes

gRPC interceptor returned nil response

grpc.*interceptor.*returned nil.*error

  • Always return response from handler call
  • Don't swallow handler errors in interceptor
go3 fixes

GORM scan destination not pointer

gorm.*scan.*destination.*not a pointer

  • Pass &result to Scan/Find methods
  • Use pointer to struct or slice
go3 fixes

Context cancel function not called (leak)

context\.WithCancel.*leak.*cancel not called

  • Defer cancel() immediately after WithCancel
  • Use errgroup which manages context
go3 fixes

JSON unmarshal type mismatch

json.*cannot unmarshal.*into Go value of type

  • Match Go struct field types to JSON
  • Use json.Number for flexible number handling
go3 fixes

Build constraints exclude all files

go.*build constraints exclude all Go files

  • Check //go:build tags match target OS/arch
  • Add file for target platform
go3 fixes

Interface satisfied only by pointer receiver

interface.*method.*has pointer receiver

  • Use &T when assigning to interface
  • Declare methods on *T consistently
go3 fixes

gRPC nil response status conversion

grpc.*status\.Convert.*nil response

  • Return non-nil response or explicit error
  • Use status.Error() for error responses
go3 fixes

GORM unsupported data type for driver

gorm.*unsupported data type.*with.*driver

  • Use serializer tag for complex types
  • Implement Scan/Value for custom types
go3 fixes

Test flag not defined before Parse

testing.*flag.*not defined.*before.*flag\.Parse

  • Define flags in init() or TestMain
  • Use testing.M for custom flags
go3 fixes

Multiple return values in single-value context

multiple-value.*in single-value context

  • Assign all return values
  • Use _ for unwanted values
go3 fixes

Mutex copied by value

go vet.*copylocks.*passes lock by value

  • Pass mutex by pointer
  • Embed *sync.Mutex in struct
go3 fixes

Ambiguous import from multiple modules

go.*ambiguous import.*found.*in multiple modules

  • Use explicit module version in go.mod
  • Add replace directive for disambiguation
go3 fixes

Reflect map key type mismatch

reflect\.Value\.MapIndex.*key type mismatch

  • Convert key to map's key type
  • Use reflect.ValueOf with correct type
go3 fixes

Cgo segfault in C code

cgo.*signal.*SIGSEGV.*C code

  • Validate C pointers before dereference
  • Check C memory allocation succeeded
go3 fixes

GORM column not found in DB

gorm.*column.*does not exist

  • Run AutoMigrate to sync schema
  • Check struct tag gorm:"column:name"
go3 fixes

gRPC message exceeds max size

grpc.*received message larger than max

  • Set MaxRecvMsgSize in dial/server options
  • Implement pagination or streaming
go3 fixes

Interface type not comparable

interface.*is not.*comparable

  • Don't use interface in map keys
  • Implement custom hash/equal
go3 fixes

Fuzz test found crash

go test -fuzz.*mutator.*crash

  • Fix bug exposed by crash input
  • Add corpus entry as regression test
go3 fixes

Cannot convert to type parameter

cannot convert.*to type.*type parameter

  • Add conversion constraint to type parameter
  • Use explicit type conversion
go3 fixes

GORM Where clause invalid value

gorm.*Where.*invalid value

  • Use correct placeholder syntax (?)
  • Pass values as variadic args
go3 fixes

Go mod tidy unknown dependency

go mod tidy.*not a known dependency

  • Add missing import in source code
  • Run go get package@version first
go3 fixes

Goroutine stack overflow (deep recursion)

goroutine.*stack overflow

  • Convert recursion to iteration
  • Increase GOGC or stack limit
go3 fixes

gRPC transport connection reset

grpc.*transport.*read.*connection reset

  • Implement retry with backoff
  • Use keepalive parameters
go3 fixes

GORM delete/update without WHERE clause

gorm.*ErrMissingWhereClause.*without conditions

  • Add Where condition to query
  • Use AllowGlobalUpdate session mode
go3 fixes

Reflect method called on nil

reflect.*Method.*called on nil Value

  • Check for nil before reflect operations
  • Verify interface is not nil before Value
go3 fixes

Type assertion on type parameter

cannot use type assertion on type parameter

  • Use type switch instead
  • Convert to interface{} first (Go <1.20)
go3 fixes

Cgo disallowed GCC flags

cgo.*gcc.*flag.*not allowed

  • Use CGO_CFLAGS_ALLOW regex to permit flags
  • Remove non-standard flags
go3 fixes

Test cleanup function panicked

testing.*cleanup.*func.*panic

  • Add recover in cleanup function
  • Fix resource cleanup logic
go3 fixes

JSON unmarshal to interface failure

json.*Unmarshal.*cannot.*interface

  • Unmarshal to concrete type
  • Use json.RawMessage for deferred parsing
go3 fixes

Go checksum mismatch

go.*sum.*mismatch.*GONOSUMCHECK

  • Run go mod download to refresh
  • Set GONOSUMCHECK for specific modules
go3 fixes

gRPC client connection not ready

grpc.*client.*connection.*IDLE.*not ready

  • Use grpc.WithBlock() for blocking dial
  • Implement WaitForReady option on calls
go3 fixes

GORM DryRun session error

gorm.*Session.*DryRun.*error

  • Use separate session for DryRun
  • Don't chain DryRun with real operations
go3 fixes

Cannot embed type parameter in struct

cannot embed.*type parameter

  • Use named field instead of embedding
  • Add interface constraint for method access
go3 fixes

Printf format verb type mismatch

go vet.*printf.*wrong type.*at.*arg

  • Match format verb to argument type
  • Use %v for generic formatting
go3 fixes

Select on all nil channels blocks forever

select.*all channels nil.*permanent block

  • Add default case to select
  • Ensure at least one non-nil channel
go3 fixes

gRPC server listener closed

grpc.*server.*serve.*listener closed

  • Handle server.GracefulStop() properly
  • Don't close listener separately from server
go3 fixes

GORM many-to-many junction table missing

gorm.*many2many.*junction table.*not found

  • Run AutoMigrate for both models
  • Specify joinTable in struct tag
go3 fixes

Go coverage no test files found

go test.*coverage.*no test files

  • Create _test.go file in package
  • Check build tags don't exclude tests
go3 fixes

Type element constraint cannot be used as type

constraint.*interface contains type elements.*cannot be used

  • Use constraint only in type parameter position
  • Create interface without type elements for variables
go3 fixes

sync.Pool returned nil

sync.*Pool.*Get.*returned nil

  • Always set Pool.New function
  • Check for nil after Get and allocate
go3 fixes

Go HTTP server TLS handshake error

http.*server.*TLS handshake error

  • Verify certificate and key file paths
  • Check certificate chain is complete
go3 fixes

gRPC metadata key invalid format

grpc.*metadata.*key.*invalid

  • Use lowercase ASCII for metadata keys
  • Use -bin suffix for binary metadata
go3 fixes

GORM rows already closed

gorm.*Rows.*already closed

  • Process rows before closing
  • Don't call Rows() result after Close
go3 fixes

Go embed pattern matches nothing

go.*embed.*pattern.*matches no files

  • Fix embed path relative to Go file
  • Check file exists at specified path
go3 fixes

Atomic 64-bit misalignment on 32-bit

atomic.*misaligned.*64-bit.*address

  • Place atomic int64 first in struct
  • Use atomic.Int64 type (Go 1.19+)
go3 fixes

Nil pointer dereference detected

go vet.*nilness.*nil dereference

  • Add nil check before dereference
  • Return early on nil value
go3 fixes

Interface method signature mismatch

interface method.*has different.*signature

  • Match method signature exactly
  • Check parameter and return types
go3 fixes

GORM Save requires primary key

gorm.*Save.*primary key required

  • Set ID field before calling Save
  • Use Create() for new records without PK
go3 fixes

Race between test cleanup and goroutine

testing.*race.*between test cleanup and goroutine

  • Wait for goroutines before test ends
  • Use sync.WaitGroup in test
go3 fixes

Untyped nil for generic type parameter

cannot use.*\(untyped nil\).*as.*type parameter

  • Use typed nil: (*Type)(nil)
  • Initialize with zero value of type
go3 fixes

Consul Health Check Critical - Deregistered

Consul.*agent.*check.*critical.*deregistered

  • Fix failing health check endpoint
  • Increase deregister timeout in service definition
go3 fixes

gRPC Service Unavailable

gRPC.*UNAVAILABLE.*upstream.*connect.*error

  • Implement retry with backoff in gRPC client
  • Check service is running and port is correct
go3 fixes

gRPC Deadline Exceeded

gRPC.*DEADLINE_EXCEEDED.*timeout

  • Increase deadline/timeout in client context
  • Optimize server processing time
go3 fixes

gRPC Message Size Exceeded

gRPC.*RESOURCE_EXHAUSTED.*message.*size

  • Increase MaxRecvMsgSize on server and MaxCallRecvMsgSize on client
  • Paginate large responses instead of single message
go3 fixes

gRPC Method Not Implemented

gRPC.*UNIMPLEMENTED.*method.*not found

  • Verify service proto is compiled and registered
  • Check client and server use same proto version
go3 fixes

gRPC Metadata Not Propagating

gRPC.*metadata.*header.*propagation.*lost

  • Extract and forward metadata in interceptors
  • Use metadata.FromIncomingContext() in handler
go3 fixes

Consul Connect Intention Denied

consul.*connect.*intention.*denied

  • Create intention allowing source → destination service
  • Check intention priority (deny takes precedence)
go3 fixes

gRPC Client-Side Load Balancing Not Working

gRPC.*load.*balancing.*pick_first.*single.*backend

  • Use round_robin or grpclb policy instead of pick_first
  • Set load balancing config in service config JSON
go3 fixes

gRPC Server Reflection Not Enabled

gRPC.*server.*reflection.*not enabled

  • Register reflection service: reflection.Register(server)
  • Use grpcurl with -plaintext flag for local testing
go3 fixes

Nil pointer dereference

runtime error: invalid memory address or nil pointer dereference

  • Add nil check before accessing the pointer
  • Initialize the struct/pointer before use
go3 fixes

Undefined variable or function

undefined:.*

  • Check for typos in the identifier name
  • Import the package that defines the symbol
go3 fixes

Unused import

imported and not used:.*

  • Remove the unused import
  • Use the blank identifier: _ "package" if import is for side effects
go3 fixes

Multi-value return used as single value

multiple-value.*in single-value context

  • Assign both return values: val, err := function()
  • Use blank identifier for unused value: val, _ := function()
go3 fixes

Type mismatch in assignment or argument

cannot use.*\(.*\) as.*in

  • Perform explicit type conversion: targetType(value)
  • Check if the value needs a pointer/dereference: &val or *ptr
go3 fixes

Goroutine deadlock - all blocked

all goroutines are asleep.*deadlock

  • Ensure channels have a reader and writer (don't send to unbuffered channel with no receiver)
  • Use buffered channels if producer/consumer timing differs
go3 fixes

Variable declared but not used

declared (and|but) not used

  • Use the variable in your code
  • Remove the declaration if it's unnecessary
go3 fixes

Cannot assign to struct field or expression

cannot assign to.*\..*

  • Use a pointer receiver to modify struct fields
  • Store the struct as a pointer in the map: map[key]*Struct
go3 fixes

Interface type assertion failed

interface conversion:.*is.*not

  • Use comma-ok pattern: val, ok := iface.(Type)
  • Check the concrete type with a type switch
go3 fixes

Concurrent map access without synchronization

concurrent map (read and map write|writes)

  • Protect the map with sync.RWMutex
  • Use sync.Map for concurrent access patterns
go3 fixes

Range over non-iterable type

cannot range over.*\(type.*\)

  • Ensure the variable is a slice, array, map, channel, or string
  • Check if you need to dereference a pointer to a slice: *slicePtr
go3 fixes

Function missing return statement

missing return at end of function

  • Add a return statement at the end of the function
  • Ensure all code paths in if/else/switch return a value
go3 fixes

Context deadline/timeout exceeded

context deadline exceeded

  • Increase the timeout duration in context.WithTimeout()
  • Optimize the slow operation to complete within the deadline
go3 fixes

Send on closed channel

panic: send on closed channel

  • Ensure the channel is only closed by the sender, not the receiver
  • Use a sync.Once to close the channel exactly once
go3 fixes

Package not found in go.mod

no required module provides package.*go\.mod

  • Run go get package@version to add the dependency
  • Run go mod tidy to resolve and clean dependencies
go3 fixes

Slice bounds out of range

slice bounds out of range

  • Check slice length before slicing: if len(s) > i
  • Use min(i, len(s)) for the upper bound
go3 fixes

Cannot take address of expression

cannot take the address of

  • Assign the value to a variable first, then take its address
  • Use a helper function that returns a pointer: func ptr(v T) *T { return &v }
go3 fixes

Data race detected by race detector

data race detected

  • Protect shared state with sync.Mutex or sync.RWMutex
  • Use atomic operations for simple counters: atomic.AddInt64()
go3 fixes

File descriptor limit reached

too many open files

  • Ensure all file/connection handles are closed with defer f.Close()
  • Increase OS ulimit: ulimit -n 65536
go3 fixes

Package initialization cycle

init cycle not allowed

  • Break the cycle by moving shared types to a separate package
  • Use interfaces to decouple packages