Avoid nil pointer dereferences by explicitly checking if pointers are nil before accessing their fields or methods. Use an if statement to guard the access, ensuring the pointer is valid before proceeding.
if ptr != nil {
value := ptr.Field
// safe to use value
}
Alternatively, use the panicnil GODEBUG setting to control runtime behavior for panic(nil) in Go 1.21+, though this does not prevent dereferencing nil pointers directly. To enforce stricter checks at compile time or runtime for specific behaviors, set GODEBUG=panicnil=0 to treat panic(nil) as a runtime error, but for pointer dereferences, manual checks remain the primary defense.