A custom comparison method checks the fields or elements that determine whether two values are equal. It avoids the limits of == for slices and maps and can outperform reflect.DeepEqual when runtime performance matters. section 3.13
Compare fields explicitly
For customer values, compare id first, reject different operation lengths, then compare each operations element. Return false at the first mismatch and true only after every check succeeds. section 3.13
func (a customer) equal(b customer) bool {
if a.id != b.id { #1
return false
}
if len(a.operations) != len(b.operations) { #2
return false
}
for i := 0; i < len(a.operations); i++ { #3
if a.operations[i] != b.operations[i] {
return false
}
}
return true
}
Inspect the complete custom equal method, including early returns, length validation, and element-by-element slice comparison. section 3.13
Choose the comparison approach according to the value and context:
- Use reflect.DeepEqual as a general solution, accepting its performance penalty. section 3.13
- Use go-cmp or testify for suitable unit-test comparisons. section 3.13
- Prefer an existing optimized method such as bytes.Compare before implementing custom logic. section 3.13

