liveBook · Manning

Custom comparison method

As explained in 100 Go Mistakes and How to Avoid Them

A custom comparison method is programmer-defined comparison logic that checks the relevant fields or elements of values.

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

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines field checks, length checks, early returns, and element iteration, while omitting comparison-library internals.
Examples
Uses customer structs containing an id and operations slice, comparing matching fields and elements.
What it assumes
Assumes Go structs, slices, methods, loops, and equality operators, while demonstrating why composite values may be uncomparable.
What you can do after
Build it from scratch by implementing field-specific equality with early exits and collection-element checks.
How it connects
Connects equality methods with the == operator, slices, maps, reflect.DeepEqual, unit testing, and bytes.Compare.

Also explained in

Compare how 2 books explain custom comparison method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.