Before adding nil checks, evaluate whether they are actually necessary or if they represent false positives from static analysis tools. Consider Go's built-in nil safety patterns and semantics.
Before adding nil checks, evaluate whether they are actually necessary or if they represent false positives from static analysis tools. Consider Go’s built-in nil safety patterns and semantics.
Key principles:
len(data)
return 0 for nil slices/maps, making explicit nil checks often redundant[]string{}
(empty slice) and []string(nil)
(nil slice) have different semantics, though both have length 0Example of necessary nil check:
// NewWithClient creates a client from an existing fasthttp.Client
func NewWithClient(c *fasthttp.Client) *Client {
if c == nil {
panic("client cannot be nil")
}
return &Client{client: c}
}
Example of unnecessary nil check:
func parseToStruct(data map[string][]string) error {
// Unnecessary: len(nil) == 0 in Go
if data == nil {
return nil
}
// Better: direct length check handles nil case
if len(data) == 0 {
return nil
}
}
When in doubt, consider: “Can this value actually be nil given the calling context?” and “Does Go already handle this nil case safely?”
Enter the URL of a public GitHub repository