reflect.DeepEqual Compares Composite Values
reflect.DeepEqual compares maps, slices, and structs field by field, ignores map key order, and still reports NaN and func values as unequal.
Code
package main
import (
"fmt"
"math"
"reflect"
)
type point struct {
X int
Y int
}
func main() {
// Composite values compare field by field recursively: pointer addresses are irrelevant
fmt.Println(reflect.DeepEqual(
map[string][]int{"ids": {1, 2, 3}},
map[string][]int{"ids": {1, 2, 3}},
))
// Map comparison is independent of key order
fmt.Println(reflect.DeepEqual(
map[int]string{1: "a", 2: "b"},
map[int]string{2: "b", 1: "a"},
))
// Structs of the same type compare field by field
fmt.Println(reflect.DeepEqual(point{1, 2}, point{1, 2}))
// NaN equals nothing, not even itself
fmt.Println(reflect.DeepEqual(math.NaN(), math.NaN()))
// Func values only equal nil: two non-nil funcs are never DeepEqual
fmt.Println(reflect.DeepEqual(func() {}, func() {}))
}How it works
reflect.DeepEqual Compares Composite Values comes down to the function main.
All five comparisons live in main. The first puts two map[string][]int values with identical ids slices side by side and prints true — comparison descends into slices element by element, so pointer identity is irrelevant. The second compares two map[int]string literals written in opposite key orders and still prints true, because map equality ignores key order. The third compares two point{1, 2} structs of the same type, equal field by field. The last two print false: math.NaN() compares unequal to itself, and two distinct non-nil func() {} values are never equal.
Interactive Tools for This Topic
FAQ
- How do you run reflect.DeepEqual Compares Composite Values?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.