πŸ”§ Error Fixes
Β· 1 min read

Go: Runtime Error β€” Invalid Memory Address or Nil Pointer Dereference


runtime error: invalid memory address or nil pointer dereference

You’re trying to use a pointer that’s nil.

Why this happens

In Go, pointer variables default to nil when not explicitly initialized. When you attempt to access a field or call a method on a nil pointer, the runtime panics because there’s no memory address to dereference. This commonly occurs when functions return nil on error and the caller doesn’t check before using the result.

Fix 1: Check for nil before using

// ❌ user might be nil
fmt.Println(user.Name)

// βœ… Check first
if user != nil {
    fmt.Println(user.Name)
}

Fix 2: Initialize your structs

// ❌ Pointer is nil
var user *User
user.Name = "Alice"  // Panic!

// βœ… Initialize
user := &User{}
user.Name = "Alice"

Fix 3: Check error returns

result, err := doSomething()
if err != nil {
    log.Fatal(err)
}
// Now safe to use result
fmt.Println(result.Value)

Alternative solutions

Use value receivers instead of pointer receivers when the method doesn’t need to mutate the struct β€” this avoids nil pointer panics on method calls.

Return zero-value structs instead of nil from functions when possible:

// βœ… Returns empty struct instead of nil
func getUser() User {
    return User{}
}

Prevention

  • Always handle the error case before using the returned value β€” never skip if err != nil checks.
  • Use a linter like nilaway or staticcheck to catch potential nil dereferences at compile time.

Related: Go: Context Deadline Exceeded fix Β· C#: NullReferenceException fix