Go Error Fixes -- How to Fix Common Go Errors
Go errors like unused variable declarations and index out of range prevent compilation entirely -- this guide shows you how to diagnose and fix the most common Go compiler and runtime errors with exact code examples.
What You'll Learn
Why It Matters
Golang strict compiler catches errors early but their messages can be cryptic. Understanding each error type saves you from repeated compilation failures and helps you write idiomatic Go.
Real-World Use
When your Go microservice fails to compile due to an unused variable or panics at runtime with an index out of range, applying the correct fix keeps your service running in production.
Common Go Errors Table
| Error Message | Cause | Fix |
|---|---|---|
| undefined: fmt | Package imported but not used in code | Import only packages you actually use or use fmt.Println |
| x declared and not used | Variable declared but never read | Use the variable or replace with _ blank identifier |
| index out of range [5] with length 3 | Accessing slice index beyond length | Check slice length before access with len() |
| cannot use str (type string) as type int | Type mismatch in assignment or function arg | Convert the value to the correct type |
| assignment mismatch: 2 variables but 1 value | Wrong number of return values from function | Match the function signature's return count |
| missing return at end of function | Function declared with return but path without return | Add a return statement for all code paths |
| panic: runtime error: invalid memory address | Dereferencing a nil pointer | Check pointer is nil with if ptr == nil before use |
Step-by-Step Fixes
Fix 1: Unused Variable
// bad.go
package main
import "fmt"
func main() {
x := 10
fmt.Println("Hello")
}
// ./main.go:6:2: x declared but not used
// fixed.go
package main
import "fmt"
func main() {
x := 10
fmt.Println(x) // use x
}
// Or use blank identifier
// _ = x
Expected output:
10
Fix 2: Index Out of Range
// bad.go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
fmt.Println(nums[5]) // panic: index out of range [5] with length 3
}
// fixed.go
package main
import "fmt"
func main() {
nums := []int{1, 2, 3}
if len(nums) > 5 {
fmt.Println(nums[5])
} else {
fmt.Println("Index out of range")
}
}
Expected output:
Index out of range
Fix 3: Type Mismatch
// bad.go
package main
import "fmt"
func main() {
var age int
age = "twenty" // cannot use "twenty" (type string) as type int
fmt.Println(age)
}
// fixed.go
package main
import "fmt"
import "strconv"
func main() {
var age int
ageStr := "20"
age, _ = strconv.Atoi(ageStr) // convert string to int
fmt.Println(age)
}
Expected output:
20
Fix 4: Missing Return
// bad.go
package main
import "fmt"
func divide(a, b int) int {
if b == 0 {
fmt.Println("Cannot divide by zero")
// missing return
}
return a / b
}
// fixed.go
package main
import "fmt"
func divide(a, b int) (int, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
Expected output:
Error: cannot divide by zero
Fix 5: Nil Pointer Dereference
// bad.go
package main
import "fmt"
type User struct {
Name string
}
func main() {
var user *User
fmt.Println(user.Name) // panic: runtime error: invalid memory address
}
// fixed.go
package main
import "fmt"
type User struct {
Name string
}
func main() {
var user *User
if user != nil {
fmt.Println(user.Name)
} else {
fmt.Println("User is nil")
}
}
Expected output:
User is nil
Fix 6: Assignment Mismatch
// bad.go
package main
func getStats() (int, int) {
return 1, 2
}
func main() {
result := getStats() // assignment mismatch: 2 variables but 1 value
}
// fixed.go
package main
import "fmt"
func getStats() (int, int) {
return 1, 2
}
func main() {
a, b := getStats() // match both return values
fmt.Println(a, b) // 1 2
}
Expected output:
1 2
Go Error Diagnosis Flowchart
flowchart TD
A[Go Error Detected] --> B{Compile or Runtime?}
B -->|Compile| C{Error Type?}
C -->|Unused Variable| D[Use the var or assign to _]
C -->|Type Mismatch| E[Convert types explicitly]
C -->|Missing Return| F[Add return to all paths]
C -->|Assignment Mismatch| G[Match return value count]
B -->|Runtime| H{Error Type?}
H -->|Index Out of Range| I[Check len before access]
H -->|Nil Pointer| J[Check pointer for nil]
I --> K[Error Resolved]
J --> K
D --> K
E --> K
F --> K
G --> K
Prevention Tips
- Run
go vetbefore building to catch common errors like unused variables - Always check slice bounds with
len()before indexed access - Initialize pointers with
&Struct{}ornew(Struct)instead of leaving them nil - Use the blank identifier
_for return values you do not need - Write unit tests that cover edge cases including nil pointers and empty slices
- Enable the Go linter in your IDE to catch type mismatches as you type
- Use
go mod tidyregularly to keep dependencies clean
Practice Questions
Why does Go refuse to compile code with an unused variable? Answer: Go treats unused variables as a compile error to prevent dead code and improve code quality. Either use the variable or replace it with
_.What causes a nil pointer dereference panic? Answer: You tried to access a field or method on a pointer that was never initialized. Always check
if ptr != nilbefore dereferencing.How do you safely access a slice element that may be out of range? Answer: Check
if index < len(slice)before accessingslice[index], or use a range loop which never goes out of bounds.What does the blank identifier
_do in Go? Answer: It discards a value you do not need. Use it for unused return values or variables to satisfy the compiler.Challenge: Write a Go function that safely retrieves a value from a nested map structure with arbitrary key depth, returns a zero value for missing keys, and never panics even if intermediate maps are nil. Answer:
package main import "fmt" func safeGet(m map[string]interface{}, keys ...string) interface{} { current := interface{}(m) for _, key := range keys { if m, ok := current.(map[string]interface{}); ok { current = m[key] } else { return nil } } return current } func main() { data := map[string]interface{}{ "user": map[string]interface{}{ "name": "Alice", "age": 30, }, } fmt.Println(safeGet(data, "user", "name")) // Alice fmt.Println(safeGet(data, "user", "email")) // nil fmt.Println(safeGet(data, "missing")) // nil }
Quick Reference
| Error | Cause | Quick Fix |
|---|---|---|
| Unused variable | Declared but not read | Use it or assign to _ |
| Index out of range | Slice access beyond length | Check len(slice) before access |
| Type mismatch | Wrong type assigned | Use explicit type conversion |
| Missing return | Path with no return | Add return to every code path |
| Nil pointer | Uninitialized pointer | Check ptr == nil before use |
| Assignment mismatch | Wrong return count | Match function return signature |
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro