liveBook · Manning

Exact-match accuracy

As explained in 100 Go Mistakes and How to Avoid Them

The equality operator == compares two Go values for equality according to their types and fields.

Exact-match comparisons in Go use == only when both operands are comparable. The operator compares values according to their types and fields, so equal struct fields can produce true, while a struct containing a slice cannot be compared. section 3.13

Avoid the common mistake of applying == to every value:

  • Booleans, numerics, strings, channels, pointers, interfaces, arrays, and structs composed of comparable types support ==. section 3.13
  • Slices and maps are not comparable; a struct containing one fails at compile time. section 3.13
  • An interface comparison can panic when its dynamic value is an uncomparable type, even though the interface variables themselves are valid. section 3.13

Choose a comparison deliberately

Two customer values containing only an id can be compared with ==. After adding an operations slice, use reflect.DeepEqual for a general deep comparison or write an equal method that compares the id, lengths, and elements explicitly. 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 an explicit customer comparison that checks fields, slice lengths, and corresponding elements. section 3.13

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains comparable types, compile-time failures, interface panics, and alternatives including deep and explicit comparison.
Examples
Uses customer structs with scalar fields, slice fields, interface values, reflect.DeepEqual, and an explicit equal method.
What it assumes
Assumes familiarity with Go values, types, structs, interfaces, slices, and maps.
What you can do after
Diagnose equality failures and select ==, reflect.DeepEqual, or explicit field comparison appropriately.
How it connects
Connects equality with Go structs, slices, maps, interfaces, pointers, arrays, and reflect.DeepEqual.

Also explained in

Compare how 3 books explain exact-match accuracy →

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.