Always handle nil values explicitly in your code to improve clarity and prevent subtle bugs. When a function needs to deal with potentially nil values:
Always handle nil values explicitly in your code to improve clarity and prevent subtle bugs. When a function needs to deal with potentially nil values:
For example, instead of using a switch statement with a fall-through for nil:
func AppendGTIDInPlace(rp Position, gtid GTID) Position {
switch {
case gtid == nil:
case rp.GTIDSet == nil:
rp.GTIDSet = gtid.GTIDSet()
default:
// Handle non-nil case
}
// ...
}
Prefer explicit handling with early returns:
func AppendGTIDInPlace(rp Position, gtid GTID) Position {
// If gtid is nil, treat it as a no-op and return the input Position.
if gtid == nil {
return rp
}
if rp.GTIDSet == nil {
rp.GTIDSet = gtid.GTIDSet()
} else {
// Handle non-nil case
}
// ...
}
Also, remember that Go has built-in nil handling for some operations. For instance, append works safely with nil slices:
// This is unnecessary
if req.FilterRules != nil {
bls.Filter.Rules = append(bls.Filter.Rules, req.FilterRules...)
}
// This is sufficient
bls.Filter.Rules = append(bls.Filter.Rules, req.FilterRules...)
This approach makes the intention clear, improves code readability, and prevents unexpected behavior.
Enter the URL of a public GitHub repository