liveBook · Manning

Reflection

As explained in 100 Go Mistakes and How to Avoid Them

Reflection is the ability of a program to inspect and manipulate type and value information at runtime.

A common mistake is assuming that values stored in any are always safely comparable. Equality can compile, then panic at runtime when the dynamic value is a struct containing a slice. section 3.13

Comparing a customer with a slice

Two customer values containing identical operations slices cannot be compared with ==. Assigning them to any moves the failure from compile time to a runtime panic. Use reflect.DeepEqual for recursive comparison, or write customer.equal when the comparison needs explicit rules. DeepEqual distinguishes nil and empty collections, so choose it deliberately. section 3.13

cust1 := customer{id: "x", operations: []float64{1.}}
cust2 := customer{id: "x", operations: []float64{1.}}
fmt.Println(reflect.DeepEqual(cust1, cust2))

Run the DeepEqual example to see a customer containing a slice compare successfully. section 3.13

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Defines runtime introspection and demonstrates DeepEqual, while deferring broader reflection mechanics and documentation-specific behavior.
Examples
Uses customer structs, any values, slice fields, runtime panics, DeepEqual, and a hand-written equality method.
What it assumes
Assumes familiarity with Go structs, slices, interfaces, and equality, while introducing runtime reflection through a comparison problem.
What you can do after
Apply it via Go's reflect package to compare nested values that ordinary equality cannot compare.
How it connects
Links metaprogramming with interfaces, structs, slices, maps, pointers, functions, and equality operators.

Also explained in

Compare how 13 books explain reflection →

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.