What is reflect.DeepEqual() Function in Golang

In Golang, reflect.DeepEqual() function checks whether x and y are “deeply equal” or not. It is helpful when you want to compare complex data structures (like nested structs, maps, and slices) for equality.

Deep equality means that not only the top-level values are compared, but also their elements or fields, recursively. This differs from a shallow comparison that checks only if the pointers are equal or the top-level values are equal.

Syntax

func DeepEqual(x, y interface{}) bool

Parameters

The function accepts two arguments, x, and y, of type interface{}. This means you can pass any value to the function, and it will attempt to compare them.

Return value

It returns a boolean value, suggesting the two values are deeply equal.

Example

package main

import (
  "fmt"
  "reflect"
)

type Person struct {
  Name string
  Age int
  Hobby []string
}

func main() {
  p1 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

  p2 := Person{
    Name: "Krunal",
    Age: 30,
    Hobby: []string{"investing", "dancing"},
 }

 if reflect.DeepEqual(p1, p2) {
   fmt.Println("p1 and p2 are deeply equal")
 } else {
   fmt.Println("p1 and p2 are not deeply equal")
 }
}

Output

p1 and p2 are not deeply equal

In this example, the output will be “p1 and p2 are not deeply equal” because the two Person instances do not have the same field values, and the elements in their Hobby slices are unequal.

Keep in mind that reflect.DeepEqual() is slower than simple comparisons because it uses reflection, which incurs some performance overhead. So use it only when necessary, and prefer simpler comparison techniques whenever possible.

Example 2

package main

import (
  "fmt"
  "reflect"
)

type Person struct {
  Name string
  Age int
  Hobby []string
}

func main() {
  p1 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

  p2 := Person{
    Name: "Khushi",
    Age: 30,
    Hobby: []string{"travelling", "hiking"},
 }

 if reflect.DeepEqual(p1, p2) {
   fmt.Println("p1 and p2 are deeply equal")
 } else {
   fmt.Println("p1 and p2 are not deeply equal")
 }
}

Output

p1 and p2 are deeply equal

In this example, the output will be “p1 and p2 are deeply equal” because the two Person instances have the same field values, and the elements in their Hobby slices are equal.

That’s it.

Leave a Comment